簡體   English   中英

僅當所有匹配的記錄都已被標記時,如何刪除另一個 mysql 表中的記錄

[英]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_a 起作用並保持 table_b 不變

您可以使用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)

您可以使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM