SQL通过对行进行分组来获取常用值

时间:2012-12-22 14:11:33

标签: mysql 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_id是1和2

1 个答案:

答案 0 :(得分:4)

假设每个group_ID对于每个uid都是唯一的,(否则您需要使用distinct

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