You can't specify target table 'xxx' for update in FROM clause

Posted biehongli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了You can't specify target table 'xxx' for update in FROM clause相关的知识,希望对你有一定的参考价值。

1、执行sql语句报上面的错误:

1 DELETE 
2 FROM
3     db_student 
4 WHERE
5     RowGuid IN ( SELECT RowGuid FROM db_student WHERE age = 22 GROUP BY RowGuid HAVING count( * ) > 1 ) 
6     AND ID NOT IN ( SELECT MAX( ID ) AS id FROM db_student WHERE age = 22 GROUP BY RowGuid HAVING count( * ) > 1 )

报错如下所示
You can‘t specify target table ‘xxx‘ for update in FROM clause。

原因:因为在mysql里,不能先select一个表的记录,在按此条件进行更新和删除同一个表的记录。

详细参考:https://blog.csdn.net/h996666/article/details/81699255

 1 SELECT *
 2 FROM
 3     db_student 
 4 WHERE
 5     RowGuid IN (
 6 SELECT
 7     aa.RowGuid 
 8 FROM
 9     ( SELECT RowGuid FROM db_student WHERE age = 22 GROUP BY RowGuid HAVING count( * ) > 1 ) aa 
10     ) 
11     AND ID NOT IN (
12 SELECT
13     t.id 
14 FROM
15     ( SELECT MAX( ID ) as id FROM db_student WHERE age = 22 GROUP BY RowGuid HAVING count( * ) > 1 ) t 
16     )
17     
18 
19 DELETE 
20 FROM
21     db_student 
22 WHERE
23     RowGuid IN (
24 SELECT
25     aa.RowGuid 
26 FROM
27     ( SELECT RowGuid FROM db_student WHERE age = 22 GROUP BY RowGuid HAVING count( * ) > 1 ) aa 
28     ) 
29     AND ID NOT IN (
30 SELECT
31     t.id 
32 FROM
33     ( SELECT MAX( ID ) as id FROM db_student WHERE age = 22 GROUP BY RowGuid HAVING count( * ) > 1 ) t 
34     )

 

待续......

以上是关于You can't specify target table 'xxx' for update in FROM clause的主要内容,如果未能解决你的问题,请参考以下文章

You can't specify target table 'table' for update in FROM clause

You can't specify target table 'xxx' for update in FROM clause

mysql You can't specify target table 'xxx' for update in FROM clause的解决

You can't specify target table 't_mail_marketing' for update in FROM clause

You can't specify target table '表名' for update in FROM clause”解决方法

You can't specify target table 'e' for update in FROM clause