我有一个像这样的SQL表:
+------+------------+---------+---------+--------+
| id | x | y | z | status |
+------+------------+---------+---------+--------+
| 1 | bla | ja | 1 | 0 |
| 2 | blaa | jaa | 2 | 0 |
| 3 | bla | ja | 1 | 0 |
| 4 | blaaa | jaaa | 3 | 0 |
| 5 | blaa | jaa | 2 | 0 |
+------+------------+---------+---------+--------+
我想只更新重复行的状态列,而不是第一行。
使用该语句,我更新每个副本也是重复行的第一行:
UPDATE table INNER JOIN
(SELECT x, y, z FROM table GROUP BY x,y,z HAVING COUNT(id) > 1)
dup
ON table.x = dup.x && table.y = dup.y && table.z = dup.z
SET status = '1'
但这不对,因为该表必须像这样处理UPDATE语句:
+------+------------+---------+---------+--------+
| id | x | y | z | status |
+------+------------+---------+---------+--------+
| 1 | bla | ja | 1 | 0 |
| 2 | blaa | jaa | 2 | 0 |
| 3 | bla | ja | 1 | 1 |
| 4 | blaaa | jaaa | 3 | 0 |
| 5 | blaa | jaa | 2 | 1 |
+------+------------+---------+---------+--------+
我希望你能帮助我。
非常感谢。
答案 0 :(得分:1)
只需使用下面的选择状态,直到您有重复的列表,然后如图所示进行更新。
UPDATE table set status = '1'
WHERE ID in (select id from(Select ROW_NUMBER() OVER (Partition By x,y,z,status) as dup,id) where dup>1)
没有说RDBMS所以这是针对SQL Server的
答案 1 :(得分:0)
我相信这就是你想要的:
UPDATE table t INNER JOIN
(SELECT x, y, z, MIN(id) as minid
FROM table
GROUP BY x, y, z
HAVING COUNT(id) > 1 -- not strictly necessary, but why not?
) dup
ON t.x = dup.x AND t.y = dup.y AND t.z = dup.z AND
t.id > dup.minid
SET status = 1;
这会计算每个组的最小id
,然后更新所有其他行。