仅当所有匹配记录都已被标记时,如何删除另一个 mysql table 中的记录
How to delete records in another mysql table only if all the matching records have been flagged
table_a
user_id canon_id
1 1000
2 1000
3 1000
11 4344
7 2023
8 2023
10 2023
12 3333
table_b
user_id flag
1 0
2 0
3 1
11 1
7 1
8 1
10 1
12 0
在上面的例子中,对应于2023和4344的user_ids应该被删除但是1000和3333不应该因为有些记录是0。删除操作应该只对table [=16有效=] 并保持 table_b 完整
您可以使用 not exists
删除第一个 table(我称之为 a
)的记录,而另一个 table(称为b
) 具有相同的 user_id
和 flag
设置为 0
:
delete from a
where not exists (select 1 from b where b.user_id = a.user_id and b.flag = 0)
请注意,这也会删除 a
中在 b
中没有相应记录的记录。如果你想避免这种情况,你需要另一个子查询:
delete from a
where
not exists (select 1 from b where b.user_id = a.user_id and b.flag = 0)
and exists (select 1 from b where b.user_id = a.user_id)
您可以使用 join
:
delete a
from table_a a join
(select user_id
from table_b b
group by user_id
having sum(flag <> 1) = 0
) bu
on a.user_id = bu.user_id;
table_a
user_id canon_id
1 1000
2 1000
3 1000
11 4344
7 2023
8 2023
10 2023
12 3333
table_b
user_id flag
1 0
2 0
3 1
11 1
7 1
8 1
10 1
12 0
在上面的例子中,对应于2023和4344的user_ids应该被删除但是1000和3333不应该因为有些记录是0。删除操作应该只对table [=16有效=] 并保持 table_b 完整
您可以使用 not exists
删除第一个 table(我称之为 a
)的记录,而另一个 table(称为b
) 具有相同的 user_id
和 flag
设置为 0
:
delete from a
where not exists (select 1 from b where b.user_id = a.user_id and b.flag = 0)
请注意,这也会删除 a
中在 b
中没有相应记录的记录。如果你想避免这种情况,你需要另一个子查询:
delete from a
where
not exists (select 1 from b where b.user_id = a.user_id and b.flag = 0)
and exists (select 1 from b where b.user_id = a.user_id)
您可以使用 join
:
delete a
from table_a a join
(select user_id
from table_b b
group by user_id
having sum(flag <> 1) = 0
) bu
on a.user_id = bu.user_id;