我正在尝试使用以下查询更新子查询返回的某些行上的列。子查询选择需要更新的行的右侧ID。
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中分成两部分,但我想知道如何用一个查询更新它。感谢。
答案 0 :(得分:1)
更改WHERE EXISTS (
到WHERE Im.id IN (
答案 1 :(得分:0)
您的查询中有错误,您忘记在尝试更新的表和EXISTS中的语句之间定义连接条件
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)
此外,您的查询很复杂。 遗憾的是,我不知道您的数据库结构,但看起来您可以使用多个表中的UPDATE来简化查询 http://forums.mysql.com/read.php?20,85813,85813