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_a起作用,并保持table_b完好无损
发布于 2020-02-29 09:30:44
您可以使用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;发布于 2020-02-29 09:18:17
您可以使用not exists从第一个表(我称之为a)中删除记录,对于这些记录,在另一个表(名为b)中不存在其他记录,并且具有相同的user_id和设置为0的flag
delete from a
where not exists (select 1 from b where b.user_id = a.user_id and b.flag = 0)请注意,这还将删除在b中没有相应记录的a中的记录。如果你想避免这种情况,你需要另外一个子查询:
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)https://stackoverflow.com/questions/60461154
复制相似问题