2017-05-03 53 views
2

的選擇用戶我有一個購買的表是這樣的:誰購買了一套商品

+--------+--------+  
| UserId | ItemId |  
+--------+--------+  
|  1 |  2 |  
|  4 |  5 |  
|  5 |  3 |  
|  1 |  4 |  
+--------+--------+  

我想選擇誰購買的物品(4,5,6)中的所有用戶ID。我與這個查詢嘗試:

select distinct UserId from purchases where ItemId in (4,5,6) 

這將返回誰購買其中任何3個項目的用戶,但我只希望誰購買的物品的所有3個用戶。

有關我能做什麼的想法?我使用PostgreSQL 8

+3

Postgres的** 8 **?真?你應該計劃升級到支持和維護版本**現在** –

回答

3

匹配的having子句中count(*)集合中的項目將返回所有UserId誰購買集合中的所有項目的數量。

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 */ 

如果可以有一個給定UserIdItemId多行,那麼你可以使用count(distinct ItemId)代替。

rextester演示:http://rextester.com/QXL12068

+0

這不適合我。它只返回那些購買了這些商品3次的用戶,而不是他們購買了全部3種商品 –

+0

@TomerShemesh如果給定的UserId和ItemId可以有多行,那麼可以使用count(distinct ItemId)。 – SqlZim

+0

@ClodoaldoNeto是的。我更新了rextester演示來證明它。 – SqlZim

0
select userId 
from purchase 
group by userId 
having 
    bool_or (itemId = 4) and 
    bool_or (itemId = 5) and 
    bool_or (itemId = 6) 
相關問題