SQL:您如何仅选择任何给定组具有所有值的组?

问题描述 投票:2回答:2

给出一个像这样的表(我通过使用连接和wheres)

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

并给出一个或多个注释ID的列表。

(100, 101)

只查找帖子中没有所有给定comment_ids的帖子


因此,使用此表和(100,101)的comment_id列表,它应该返回post id(2,3),因为post id和3没有注释100和101。

使用(101)的comment_id列表,它应该返回post 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的回答中添加了“not”以使其工作,但当我使用多个评论时:

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

然后它带回所有的post_id(1,2,3)。它应该只是带回post_id(2,3)。 Post_id 1有100和102个comment_ids,因此它不能包含在查询中。

如何让它接受多个注释ID?

sql mariadb
2个回答
2
投票

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

1
投票

根据您的查询,每个帖子最多必须有3个comment_id。因此,下面是查找不具有相同的查询

        SELECT POST_ID FROM TABLE
           GROUP BY POST_ID HAVING 
       COUNT(Distinct COMMENT_ID) <3
© www.soinside.com 2019 - 2024. All rights reserved.