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

一、執行sql語句報上面的錯誤: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。ui

緣由:由於在MYSQL裏,不能先select一個表的記錄,在按此條件進行更新和刪除同一個表的記錄。spa

詳細參考:http://www.javashuo.com/article/p-besvqebg-bm.html.net

 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     )

 

待續......code

相關文章
相關標籤/搜索