Using EXISTS with MySQL

半世苍凉 提交于 2020-01-05 10:16:14

问题


I have this simple query that works on all other database systems, but fails with MySQL:

UPDATE points p 
SET p.userid = 5224 
WHERE p.userid = 2532 
AND NOT EXISTS (
    SELECT 1
    FROM points q
    WHERE q.userid = 5224
    AND q.game = p.game
)

I get the following error message:

#1093 - You can't specify target table 'p' for update in FROM clause

Is there any workaround?


回答1:


You can't alias the main table in an UPDATE clause. This should work:

UPDATE points 
SET userid = 5224 
WHERE userid = 2532 
AND NOT EXISTS (
    SELECT 1
    FROM points q
    WHERE q.userid = 5224
    AND q.game = points.game
)



回答2:


Use:

UPDATE POINTS
   SET userid = 5224 
 WHERE userid = 2532 
   AND game NOT IN (SELECT q.game
                      FROM POINTS q
                     WHERE q.userid = 5224)


来源:https://stackoverflow.com/questions/1805009/using-exists-with-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!