仅当所有匹配的记录都已被标记时,如何删除另一个mysql表中的记录

问题描述 投票:1回答:2
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_id,但不应删除1000和3333,因为某些记录为0。删除操作应仅对表table_a起作用并保持table_b不变

mysql sql join sql-delete
2个回答
1
投票

您可以使用not exists从第一个表(我称其为a)中删除记录,而在另一个表(称为b)中没有其他记录,且具有相同的user_idflag设置为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)

0
投票

您可以使用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;
© www.soinside.com 2019 - 2024. All rights reserved.