Using EXISTS with MySQL

2019-07-31 07:58发布

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?

2条回答
何必那么认真
2楼-- · 2019-07-31 08:13

Use:

UPDATE POINTS
   SET userid = 5224 
 WHERE userid = 2532 
   AND game NOT IN (SELECT q.game
                      FROM POINTS q
                     WHERE q.userid = 5224)
查看更多
仙女界的扛把子
3楼-- · 2019-07-31 08:19

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
)
查看更多
登录 后发表回答