使用下表:
"id" "type" "parent" "country" "votes" "perCent"
"1" "1" "0" "US" "0" "0"//Appears as 0, should be 12
"2" "2" "1" "US" "0" "0"//Appears as 0, should be 8
"3" "3" "2" "US" "4" "0"
"7" "3" "2" "US" "4" "0"
"19" "3" "1" "US" "4" "0"
"4183" "10" "3" "US" "2" "0"
"4184" "10" "3" "US" "2" "0"
"4185" "10" "7" "US" "2" "0"
"4186" "10" "7" "US" "2" "0"
"4187" "10" "19" "US" "2" "0"
"4188" "10" "19" "US" "2" "0"
当我运行以下查询来更新总计时,为什么row id 1和row id 2显示为0?
UPDATE likesd a
INNER JOIN
(
SELECT parent, country, SUM(votes) totalVotes
FROM likesd
GROUP BY parent
) b ON a.id = b.parent and a.country = b.country
SET a.votes = b.totalVotes; select * from likesd;
当我这样做时:
SELECT parent, country, SUM(votes) totalVotes
FROM likesd
GROUP BY parent;
我可以看到结果中的所有行,但前两行不会更新。
我的sql出错了吗?我该怎么做呢?另外,你在我使用的sql中看到任何问题吗?
答案 0 :(得分:1)
您还应该在更新时检查国家/地区时将国家/地区也放在group by子句中。
UPDATE likesd a
INNER JOIN
(
SELECT parent, country, SUM(votes) totalVotes
FROM likesd
GROUP BY parent, country
) b ON a.id = b.parent and a.country = b.country
SET a.votes = b.totalVotes; select * from likesd;
修改强> 如果出现意外结果,您可以尝试使用update语句 -
UPDATE Likesd a
SET Voltes = (SELECT SUM(Votes)
FROM Likesd b
WHERE b.PARENT = a.Id
AND b.Country = a.Country)