给定一个像这样的表(我通过使用连接和wheres得到的)
| post_id | comment_id |
| 1 | 100 |
| 1 | 101 |
| 1 | 102 |
| . 2 . | . 100 . |
| . 3 . | . 101 . |
| . 3 . | . 102 . |
并给出一个或多个评论 ID 的列表。
(100, 101)
仅查找帖子不包含全部给定comment_ids的帖子
因此,使用此表和 comment_id 列表 (100,101),它应该返回帖子 id (2,3),因为帖子 id 2 和 3 不会同时具有评论 100 和 101。
comment_id 列表为 (101),它应该返回帖子 ID (2)。
comment_id 为 (103) 时,它应该返回 post_id (1,2,3),因为这些帖子没有评论 103(该评论不存在)。
编辑:
我只需要使用这段代码输入一个comment_id就可以让它工作。
select post_id
from table_name
group by post_id
having count(*) = sum( comment_id not in (100) )
我在戈登的回答中添加了“不”以使其正常工作,但是当我使用多个评论时,例如:
having count(*) = sum( comment_id not in (100, 102) )
然后它会返回所有的 post_ids (1,2,3)。它应该只带回 post_id (2,3)。 Post_id 1 同时具有 100 和 102 个 comment_ids,因此它不能包含在查询中。
如何让它接受多个评论 ID?
最佳答案
您可以使用group by
和having
:
select post_id
from t
group by post_id
having count(*) = sum( comment_id in (2, 3) );
这假设该表没有重复项。如果这是可能的,那么:
having count(distinct comment_id) = count(distinct case when comment_id in (2, 3) then comment_id end)
编辑:
我一定是误读了原帖。我以为你想要那些拥有所有评论的人。所以你想要:
select post_id
from t
group by post_id
having 2 <> sum( comment_id in (2, 3) );
关于SQL:如何仅选择任何给定组具有给定所有值的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913331/