1

我需要一些代码方面的帮助

我有一个名为“stuff”的数据库表,我有以下信息:

+------+-------------+---------------------+
| id   | member_id   |     group_id        |
+------+-------------+---------------------+
| 1    |      11     |         aa          |
+------+-------------+---------------------+
| 2    |      22     |         aa          |
+------+-------------+---------------------+
| 3    |      33     |         aa          |
+------+-------------+---------------------+
| 4    |      44     |         bb          |
+------+-------------+---------------------+
| 5    |      55     |         bb          |
+------+-------------+---------------------+
| 6    |      66     |         bb          |
+------+-------------+---------------------+

如果我从一个组中搜索所有 3 个成员,我需要找到组 ID

就像是:

SELECT group_id 
FROM stuff 
WHERE member_id=11 and member_id=22 and member_id=33 

我知道查询它不是有效的,但我不知道如何使它有效。

非常感谢你。

4

1 回答 1

2

问题被称为Relational Division

SELECT  group_id
FROM    stuff
WHERE   member_id IN (11,22,33)
GROUP   BY group_id
HAVING  COUNT(*) = 3

如果member_id不是每个唯一的group_id,您需要拥有DISTINCT才能仅计算唯一值。

SELECT  group_id
FROM    stuff
WHERE   member_id IN (11,22,33)
GROUP   BY group_id
HAVING  COUNT(DISTINCT member_id) = 3

此链接的更多变体:

于 2013-10-13T01:26:09.073 回答