为什么这个更新语句不应该更新所有行?

时间:2013-09-29 06:38:20

标签: mysql sql

我希望以下查询会更新updated=0所有的行,但事实并非如此。它只进行一次更新。你能明白为什么吗?

UPDATE scores t1
JOIN scores t2
ON FIND_IN_SET(t1.id, t2.vals)
SET t1.total = t1.total  + 1
WHERE t2.updated = 0;

运行查询前的表格

"id"    "total" "vals"  "updated"
"1"     "0"     ""      "0"
"2"     "0"     ""      "0"
"3"     "0"     ""      "0"
"4"     "0"     "1,2,3" "0"
"5"     "0"     "1,2"   "0"

期望的结果

"id"    "total" "vals"  "updated"
"1"     "2"     ""      "0"
"2"     "2"     ""      "0"
"3"     "1"     ""      "0"
"4"     "0"     "1,2,3" "0"
"5"     "0"     "1,2"   "0"

我得到了什么

"id"    "total" "vals"  "updated"
"1"     "1"     ""      "0"
"2"     "1"     ""      "0"
"3"     "1"     ""      "0"
"4"     "0"     "1,2,3" "0"
"5"     "0"     "1,2"   "0"

由于update scores set totals = 1 where updated = 0更新了所有行,因此也应该有效。

1 个答案:

答案 0 :(得分:3)

UPDATE只更新符合条件的每一行,每次匹配连接表中的不同行时,它不会执行SET子句。您可以使用此查询来计算匹配数,并按该数字递增。

UPDATE scores t1
JOIN (
    SELECT t1.id id, COUNT(*) matches
    FROM scores t1
    JOIN scores t2
    ON FIND_IN_SET(t1.id, t2.vals)
    WHERE t2.updated = 0
    GROUP BY id) t2
ON t1.id = t2.id
SET total = total + matches,
    updated = 1

FIDDLE