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    |
...

如何为某些uid集合获取通用的group_id集合.

对于例如
对于uid 1,2:常见的group_id是1,2,3
对于uid 1,2,3:常见的group_id是1和2

最佳答案
假设每个group_ID对于每个uid都是唯一的(否则你需要使用distinct)

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

> SQLFiddle Demo (includes two queries)

转载注明原文:mysql – SQL通过对行进行分组来获取常用值 - 代码日志