首页 > 解决方案 > SQL:你如何只选择任何给定组具有所有给定值的组?

问题描述

给定这样的表(我通过使用连接和 wheres 得到)

| post_id | comment_id |
|    1    |     100    |
|    1    |     101    |
|    1    |     102    |
| .  2 .  | .   100 .  |
| .  3 .  | .   101 .  |
| .  3 .  | .   102 .  |

并给出一个或多个评论 ID 的列表。

(100, 101)

仅查找帖子不包含所有给定 comment_id的帖子


因此,使用此表和 (100,101) 的 comment_id 列表,它应该返回帖子 ID (2,3),因为帖子 ID 2 和 3 没有评论 100 和 101。

对于 (101) 的 comment_id 列表,它应该返回帖子 id (2)。

对于 (103) 的 comment_id,它应该返回 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) )

我从 Gordon 的回答中添加了“不”以使其正常工作,但是当我使用多个评论时,例如:

having count(*) = sum( comment_id not in (100, 102) )

然后它会带回所有 post_ids (1,2,3)。它应该只带回 post_id (2,3)。Post_id 1 同时具有 100 和 102 个 comment_id,因此它不能包含在查询中。

如何让它接受多个评论 ID?

标签: sqlmariadb

解决方案


您可以使用group byhaving

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) );

推荐阅读