2012-12-22 128 views
5

假設我有一個表像這樣獲得共同的價值觀:SQL通過分組行

| uid | group_id | 
----------------- 
| 1 |  1 | 
| 1 |  2 | 
| 1 |  3 | 
| 1 |  4 | 
| 2 |  1 | 
| 2 |  2 | 
| 2 |  3 | 
| 3 |  1 | 
| 3 |  2 | 
| 3 |  4 | 
... 

我怎樣才能得到一組共用的group_ids一些一套uids

例如,
爲UID 1,2:常見的group_ids是1,2,3
爲UID 1,2,3:常見的group_ids是1和2

回答

3

假設每個group_ID是獨特每uid,(否則你需要使用distinct

SELECT group_ID 
FROM tableName 
WHERE uid IN (1,2,3) 
GROUP BY group_ID 
HAVING COUNT(*) = 3