这是一个有代表性的数据样本。在第一个表中,第2行和第3行不正确。仅当存在状态为B的行且表2中不存在状态为C的行时,表1中的行才应处于活动状态。
+----+--------+--+ +-----+-----+--------+
| ID | ACTIVE | | | ID | REF | STATUS |
+----+--------+--+ +-----+-----+--------+
| 1 | 0 | | | 9 | 1 | A |
| 2 | 1 | | | 100 | 2 | A |
| 3 | 1 | | | 103 | 2 | B |
| 4 | 1 | | | 104 | 2 | C |
+----+--------+--+ | 111 | 3 | A |
| 123 | 4 | A |
| 126 | 4 | B |
+-----+-----+--------+
如何根据这些规则将第2行和第3行中的活动设置为0?
答案 0 :(得分:2)
您可以使用update
以及您描述的逻辑:
update t1
set active = (case when exists (select 1 from t2 where t2.ref = t1.id and t2.status = 'B') and
not exists (select 1 from t2 where t2.ref = t1.id and t2.status = 'C')
then 1 else 0
end);
答案 1 :(得分:1)
如果您只想更新应该为零的行,并且只保留其他所有内容,则可以使用
UPDATE TABLE_A A
SET A.ACTIVE = 0
WHERE A.A_ID IN
( SELECT b.ref
FROM TABLE_B B
WHERE NOT EXISTS (SELECT 1
FROM TABLE_B
WHERE STATUS = 'B'
AND B.REF = REF)
OR EXISTS
(SELECT 1
FROM TABLE_B
WHERE STATUS = 'C'
AND B.REF = REF))
AND a.active<>0;