我有以下表格结构,用于定义帖子及其类别之间的关系。
Post_id | Category_id
---------------------
1 | A
1 | B
1 | C
2 | A
2 | B
2 | C
2 | D
所以我想搜索有两个给定类别的帖子(例如A和B) 然后删除A行。 结果将是:
Post_id | Category_id
---------------------
1 | B
1 | C
2 | B
2 | C
2 | D
如何实现这一目标?
答案 0 :(得分:1)
试试这个:
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'
答案 1 :(得分:0)
您可以通过以下方式找到帖子:
select post_id
from post_categories
where category_id in ('A', 'B')
group by post_id
having count(distinct category_id) = 2;
然后,您可以使用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';