Sql 选择购买了一组项目的用户

Sql 选择购买了一组项目的用户,sql,postgresql,Sql,Postgresql,我有这样一个购买表: +--------+--------+ | UserId | ItemId | +--------+--------+ | 1 | 2 | | 4 | 5 | | 5 | 3 | | 1 | 4 | +--------+--------+ 我想选择所有购买物品的用户ID(4,5,6)。我正在尝试此查询: select

我有这样一个购买表:

+--------+--------+     
| UserId | ItemId |     
+--------+--------+     
|      1 |      2 |     
|      4 |      5 |     
|      5 |      3 |    
|      1 |      4 |     
+--------+--------+     
我想选择所有购买物品的用户ID(4,5,6)。我正在尝试此查询:

select distinct UserId from purchases where ItemId in (4,5,6) 
这将返回购买了这3个项目中任何一个的用户,但我只想要购买了所有3个项目的用户

对我能做什么有什么想法吗?我正在使用PostgreSQL 8。

having
子句中的
计数(*)
与集合中的项目数匹配,将返回购买集合中所有项目的所有
用户ID

select UserId 
from purchases 
where ItemId in (4,5,6) 
group by UserId
having count(distinct ItemId) = 3 /*  3 is the number of items to match the set */
如果给定的
UserId
ItemId
可以有多行,则可以使用
count(distinct ItemId)


rextester演示:

Postgres 8?真正地您现在应该计划升级到受支持和维护的版本。这对我不起作用。它只返回购买了其中任何一项3次的用户,而不是他们购买了所有3项items@TomerShemesh如果一个给定的UserId和ItemId可以有多行,那么您可以使用count(不同的ItemId)。@ClodoaldoNeto-Yes会的。我更新了rextester演示来证明这一点。
select userId
from purchase
group by userId
having
    bool_or (itemId = 4) and
    bool_or (itemId = 5) and
    bool_or (itemId = 6)