日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql: you can't specify target table 问题解决

發布時間:2025/3/15 数据库 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql: you can't specify target table 问题解决 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先創建一個表:

CREATE TABLE `t1` ( `id` INT(11) NULL DEFAULT NULL, `name` VARCHAR(20) NULL DEFAULT NULL )

插入幾條數據:

mysql> select * from t1; +------+------+ | id | name | +------+------+ | 1 | chen | | 2 | li | | 3 | huan | +------+------+ 3 rows in set (0.00 sec)

?

需求1:刪除最大id的那條記錄,于是我們會大約寫出如下的語句:

mysql> delete from t1 where id=(select max(id) from t1); ERROR 1093 (HY000): You can't specify target table 't1' for update in FROM clause
很不幸,它報錯了.

可以修改成如下語句:

mysql> delete a from t1 a,(select max(id) maxid from t1) b where a.id=b.maxid; Query OK, 1 row affected (0.01 sec)mysql> select * from t1; +------+------+ | id | name | +------+------+ | 1 | chen | | 2 | li | +------+------+ 2 rows in set (0.00 sec)

也可以是如下語句:

mysql> delete from t1 where id in ( select a.maxid from (select max(id) maxid from t1) a); Query OK, 1 row affected (0.01 sec)mysql> select * from t1; +------+------+ | id | name | +------+------+ | 1 | chen | +------+------+ 1 row in set (0.00 sec)

?

需求2:插入一條記錄,并且id值是之前該表最大值加1,于是我們會大約寫出如下的語句:

mysql> insert into t1 values( (select max(id)+1 from t1),'you'); ERROR 1093 (HY000): You can't specify target table 't1' for update in FROM clause
依舊報了同樣的錯誤

可以改寫如下:

mysql> insert into t1 select (select max(id)+1 maxid from t1 ) , 'you'; Query OK, 1 row affected (0.06 sec) Records: 1 Duplicates: 0 Warnings: 0mysql> select * from t1; +------+------+ | id | name | +------+------+ | 1 | chen | | 2 | you | +------+------+ 2 rows in set (0.00 sec)

?

需求3:我們要更新一條語句,id需要變為之前最大值加1,于是我們會大約寫出如下的語句:?

mysql> update t1 set id=(select max(id)+1 from t1) where id=1; ERROR 1093 (HY000): You can't specify target table 't1' for update in FROM clause
錯誤如初

我們可以改寫為如下語句:

mysql> update t1,(select max(id)+1 as maxid from t1 ) a set id=a.maxid where id=1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0mysql> select * from t1; +------+------+ | id | name | +------+------+ | 3 | chen | | 2 | you | +------+------+ 2 rows in set (0.00 sec)

也可以改成如下語句:

mysql> update t1 set id=(select a.maxid from (select max(id)+1 maxid from t1) a) where id=3; Query OK, 1 row affected (0.01 sec) Rows matched: 1 Changed: 1 Warnings: 0mysql> select * from t1; +------+------+ | id | name | +------+------+ | 4 | chen | | 2 | you | +------+------+ 2 rows in set (0.00 sec)

?

總的思路是:把查詢的最大值語句轉為subquery或derived。

?

轉載于:https://www.cnblogs.com/zejin2008/p/4974166.html

總結

以上是生活随笔為你收集整理的mysql: you can't specify target table 问题解决的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。