我有一个名为 status_t 的表:
**id** **page** **status** **locked**_by
1 0 2 0
1 1 2 0
1 2 2 0
2 0 0 0
2 1 2 0
2 2 2 0
主键是( id, page) 。
在上面的例子中我想更新所有 所有页面状态 = 2 的行。
即查询应将 id = 1 的所有行更新为状态 3。因此表将变为
**id** **page** **status** **locked**_by
1 0 3 1
1 1 3 1
1 2 3 1
2 0 0 0
2 1 2 0
2 2 2 0
我已经尝试过:
SELECT * FROM status_t AS t
WHERE id IN
(SELECT id FROM status WHERE status = 0) LIMIT 10
上面的查询获取要更新的行,但我不能这样做:
UPDATE status_t as S1 WHERE id IN
(SELECT id FROM status_t WHERE status = 2)
SET S1.status = 3, S1.locked_by = 1
编辑:
上表只是一个示例。
我不想更新 WHERE id = 1 。我只想更新行,无论 id 是什么 相同 ID 的状态 = 2。 在上面的示例中,如果带有键 (2, 2) 的行的状态 = 2,则应该更新它。
最佳答案
这应该有效:
update status_t t
join (
select distinct id from status_t s
where status=2 and not exists (
select 1 from status_t ss
where s.id=ss.id and s.status <> ss.status
)
) i on i.id = t.id
set t.status = 3
内部查询选择所有 status
值均设置为 2
的 ID。它通过检查不存在具有相同 ID 和不同状态的行来实现此结果。
这是一个demo on sqlfiddle .
关于Mysql 帮助更新具有相同值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13624038/