[英]Update mysql table only if all entries of another table match a certain condition
is it possible in MySQL to update a certain table only if all of the rows of another table match a certain condition?只有当另一个表的所有行都符合某个条件时,MySQL 是否可以更新某个表? Let me give you an example with a database having two tables:
让我举个例子,数据库有两个表:
TableA: id INT, completed BOOLEAN表A:id INT,完成 BOOLEAN
TableB: total INT, progress INT, tableA_id INT TableB:总INT,进度INT,tableA_id INT
Can I update TableA setting 'completed=1' if all of the entries of TableB have total==progress?如果 TableB 的所有条目都有 total==progress,我可以更新 TableA 设置“完成 = 1”吗? I was thinking about using CASE:
我在考虑使用 CASE:
UPDATE TableA SET completed = CASE WHEN (SELECT..) THEN 1 ELSE 0 END WHERE id = x
Of course I don't know how to proceed... Thank you in advance for any help!当然我不知道如何继续......提前感谢您的帮助!
Use a correlated subquery in the WHERE
clause of the UPDATE
statement which checks the min value of the boolean expression total = progress
.在
UPDATE
语句的WHERE
子句中使用相关子查询,检查 boolean 表达式total = progress
的最小值。
If it is 1
which means true
, then there is no row in TableB
where total <> progress
:如果它是
1
表示true
,那么TableB
中没有total <> progress
的行:
UPDATE TableA a
SET a.completed = 1
WHERE (SELECT MIN(b.total = b.progress) FROM TableB b WHERE b.tableA_id = a.id) = 1; -- For MySql you may even omit =1
If there is always at least 1 row in TableB
for each TableA.id
you could also use NOT EXISTS
:如果每个
TableA.id
在TableB
中始终至少有 1 行,您也可以使用NOT EXISTS
:
UPDATE TableA a
SET a.completed = 1
WHERE NOT EXISTS (
SELECT *
FROM TableB b
WHERE b.tableA_id = a.id AND b.total <> b.progress
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.