简体   繁体   English

删除具有相同ID的不同行上的多个位置-MySQL

[英]Delete with multiple where on different rows for same id - MySQL

I have the following table structure that define the relationship between posts and their categories. 我具有以下表结构,用于定义帖子及其类别之间的关系。

Post_id | Category_id
---------------------
1       | A
1       | B
1       | C
2       | A
2       | B
2       | C
2       | D

So i want to search the post that have two given categories (For example A and B) and then delete the row A. So the result would be: 所以我想搜索具有两个给定类别(例如A和B)的帖子,然后删除行A。因此结果将是:

Post_id | Category_id
---------------------
1       | B
1       | C
2       | B
2       | C
2       | D

How can achieve this? 如何实现呢?

Try this: 尝试这个:

delete t1 
from yourtable t1
join (
    -- This sub query will retrieve records that have both A and B for each `Post_id`
    select Post_id
    from yourtable
    where Category_id in ('A', 'B')
    group by Post_id
    having count(distinct Category_id) = 2
) t2
-- Then join this sub query on your table.
on t1.Post_id = t2.Post_id
where t1.Category_id = 'A'

Demo Here 在这里演示

You can find the posts by doing: 您可以通过以下方式找到帖子:

select post_id
from post_categories
where category_id in ('A', 'B')
group by post_id
having count(distinct category_id) = 2;

You can then delete them with a join : 然后可以使用join删除它们:

delete pc
    from post_categories pc join
         (select post_id
          from post_categories
          where category_id in ('A', 'B')
          group by post_id
          having count(distinct category_id) = 2
         ) todelete
         on pc.post_id = todelete.post_id
    where pc.category_id = 'A';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM