今天写mysql的时候出现了You can’t specify target table for update in FROM clause问题,错误的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)。
代码:
出现上述问题
DELETE FROM ps as p where p.id in
(SELECT id FROM ps GROUP BY id,user_id having (count(*)>1))
但是执行下述查询语句完全没有问题
select * FROM ps as p where p.id in
(SELECT id FROM ps GROUP BY id,user_id having (count(*)>1))
解决方法:
将select出的结果通过中间表select一遍,这样就规避了错误。
注意,这个问题只出现于mysql,mssql和Oracle不会出现此问题。
DELETE from ps where id in
(select a.id from
(SELECT id FROM ps GROUP BY id,user_id having (count(*)>1)) a)