2012-10-10 108 views
0

我試圖使用以下查詢來更新子查詢返回的某些行上的列。子查詢選擇需要更新的行的正確ID。如何根據select語句更新行

UPDATE 4_dev.Images AS Im 
     SET Im.primary=1 
     WHERE EXISTS (
SELECT Img.imageId FROM (
SELECT I.id AS imageId, 
     I.userId, 
     I.date, 
     SUM(I.primary) AS hasPrimary, 
     COUNT(*) AS numImages 
FROM 4_dev.Images AS I 
GROUP BY I.userId 
HAVING numImages>=1 AND hasPrimary=0) AS Img) 

但此查詢更新每一行,而不僅僅是在SELECT子查詢中的行。

這將很容易在PHP中分成兩部分,但我想知道如何用一個查詢來更新它。謝謝。

回答

1

變化WHERE EXISTS (WHERE Im.id IN (

0

你在查詢一個錯誤,你忘了定義連接表之間的條件,您嘗試更新和聲明中是否存在

UPDATE 4_dev.Images AS Im 
    SET Im.primary=1 
WHERE EXISTS (
    SELECT Img.imageId 
    FROM (
    SELECT I.id AS imageId, 
     I.userId, 
     I.date, 
     SUM(I.primary) AS hasPrimary, 
     COUNT(*) AS numImages 
    FROM 4_dev.Images AS I 
    GROUP BY I.userId 
    HAVING numImages>=1 AND hasPrimary=0) AS Img 
    WHERE Img.imageId = Im.id) 

而且您的查詢是複雜的。 不幸的是我不知道你的數據庫結構,但看起來像你可以使用來自多個表的更新來簡化你的查詢 http://forums.mysql.com/read.php?20,85813,85813