2009-11-26 213 views
1

EXISTS我已經不再需要其他所有數據庫系統的工作原理,但無法與MySQL這個簡單的查詢:使用與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 
) 

我收到以下錯誤信息:

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

有任何解決方法?

回答

3

您不能在UPDATE子句中將主表別名化。這應該工作:

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 
) 
+0

和什麼有關AND q.game = p.game? – 2009-11-26 18:11:34

+0

對不起,我錯過了一個p。我現在已將它改爲點。 – 2009-11-26 18:13:23

2

用途:

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

僅供參考:在MySQL中'NOT IN'比'NOT EXISTS'快:http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null -mysql/ – 2009-11-26 18:16:18

+0

謝謝。 +1,但我更喜歡Mark的答案,因爲NOT IN在其他數據庫系統上速度較慢,而且差別很大(索引與無索引),因此它更具可移植性。 – 2009-11-26 18:20:25

+0

@Milan:'NOT EXISTS'&'NOT IN'在SQL Server中是等同的:http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is -null-sql-server/ – 2009-11-26 18:35:48