根据UserId检索特定的GroupId

时间:2019-01-05 09:31:00

标签: mysql sql

在这种情况下,我们想检索特定的GroupId号。例如,只有3个用户的6个用户说该特定组的UserId为2、1、3个

这是我尝试执行的查询

SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3) AND userid IN (1, 2, 3);

SQL Fiddle DEMO

下面是上述查询中的详细信息,这些细节已细分

SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3

group_id
5
6

SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3)

group_id
5
5
5
6
6
6

SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3) AND userid IN (1, 2, 3)

group_id
5
5
6
6
6

SELECT group_id FROM group_users WHERE group_id IN(SELECT group_id FROM group_users GROUP BY group_id HAVING COUNT(*)=3) AND userid=1 AND userid=2 and userid = 3

group_id
NULL

预期结果:

group_id
6

由于只有一个group_id = 6的群组,其中3个用户拥有唯一的userid = 1, 2, 3

因此必须在最终结果中检索group_id = 6

2 个答案:

答案 0 :(得分:2)

HAVING子句中使用条件计数。在MySQL中,您可以简单地总结满足的条件,因为在MySQL中为true = 1和false = 0。

SELECT group_id
FROM group_users 
GROUP BY group_id 
HAVING SUM(userid IN (1, 2, 3)) = 3
   AND SUM(userid NOT IN (1, 2, 3)) = 0;

另一种甚至更简单的选择是连接用户ID并检查字符串:

HAVING GROUP_CONCAT(userid ORDER BY userid) = '1,2,3';

答案 1 :(得分:1)

所以,你是对的。您必须与正好有3个用户的组相交,而组中至少包含3个用户(1、2、3)。

Maria DB 10.2以上版本

SELECT group_id FROM group_users 
GROUP BY group_id 
HAVING COUNT(*)=3
INTERSECT
SELECT group_id FROM group_users 
WHERE userid IN (1, 2, 3)
GROUP BY group_id 
HAVING COUNT(*)=3

Click Here

对于MySQL 5.6,

SELECT DISTINCT a.group_id FROM
(SELECT group_id FROM group_users 
GROUP BY group_id 
HAVING COUNT(*)=3) a,
(SELECT group_id FROM group_users 
WHERE userid IN (1, 2, 3)
GROUP BY group_id 
HAVING COUNT(*)=3) b
WHERE a.group_id=b.group_id

Click Here