首先创建一个表:

  1. CREATE TABLE `t1` (
  2. `id` INT(11) NULL DEFAULT NULL,
  3. `name` VARCHAR(20) NULL DEFAULT NULL
  4. )

插入几条数据:

  1. mysql> select * from t1;
  2. +——+——+
  3. | id | name |
  4. +——+——+
  5. | 1 | chen |
  6. | 2 | li |
  7. | 3 | huan |
  8. +——+——+
  9. 3 rows in set (0.00 sec)
 

需求1:删除最大id的那条记录,于是我们会大约写出如下的语句:

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

可以修改成如下语句:

  1. mysql> delete a from t1 a,(select max(id) maxid from t1) b where a.id=b.maxid;
  2. Query OK, 1 row affected (0.01 sec)
  3.  
  4. mysql> select * from t1;
  5. +——+——+
  6. | id | name |
  7. +——+——+
  8. | 1 | chen |
  9. | 2 | li |
  10. +——+——+
  11. 2 rows in set (0.00 sec)

也可以是如下语句:

  1. mysql> delete from t1 where id in ( select a.maxid from (select max(id) maxid from t1) a);
  2. Query OK, 1 row affected (0.01 sec)
  3.  
  4. mysql> select * from t1;
  5. +——+——+
  6. | id | name |
  7. +——+——+
  8. | 1 | chen |
  9. +——+——+
  10. 1 row in set (0.00 sec)

需求2:插入一条记录,并且id值是之前该表最大值加1,于是我们会大约写出如下的语句:

  1. mysql> insert into t1 values( (select max(id)+1 from t1),‘you’);
  2. ERROR 1093 (HY000): You can‘t specify target table ‘t1‘ for update in FROM clause
    依旧报了同样的错误

可以改写如下:

  1. mysql> insert into t1 select (select max(id)+1 maxid from t1 ) , ‘you’;
  2. Query OK, 1 row affected (0.06 sec)
  3. Records: 1 Duplicates: 0 Warnings: 0
  4.  
  5. mysql> select * from t1;
  6. +——+——+
  7. | id | name |
  8. +——+——+
  9. | 1 | chen |
  10. | 2 | you |
  11. +——+——+
  12. 2 rows in set (0.00 sec)

需求3:我们要更新一条语句,id需要变为之前最大值加1,于是我们会大约写出如下的语句:

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

我们可以改写为如下语句:

  1. mysql> update t1,(select max(id)+1 as maxid from t1 ) a set id=a.maxid where id=1;
  2. Query OK, 1 row affected (0.00 sec)
  3. Rows matched: 1 Changed: 1 Warnings: 0
  4.  
  5. mysql> select * from t1;
  6. +——+——+
  7. | id | name |
  8. +——+——+
  9. | 3 | chen |
  10. | 2 | you |
  11. +——+——+
  12. 2 rows in set (0.00 sec)

也可以改成如下语句:

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

总的思路是:把查询的最大值语句转为subquery或derived。

 
转自:https://www.bbsmax.com/A/kvJ3Xg195g/