SQL计数使用多个WHERE子句的常见匹配数

时间:2017-01-10 17:34:07

标签: mysql sql

我的表格中包含以下列:membership_id | user_id | group_id

enter image description here

我正在寻找一个SQL查询来获取2个不同用户之间的公共组数。我可以在几个查询中使用一些PHP,但我想知道是否有一种方法只使用SQL。

与用户ID 1和3一样,有3个常见组(1,5和6),因此返回的结果为3.

我做了几次测试,但到目前为止没有结果......谢谢。

4 个答案:

答案 0 :(得分:1)

您可以通过加入来实现这一目标。

试试这个:

select t1.user_id, t2.user_id, group_concat(distinct t1.group_id)
from your_table t1
join your_table t2
on t1.user_id < t2.user_id
and t1.group_id = t2.group_id
group by t1.user_id, t2.user_id;

如果您不想要连续输出:

select distinct t1.user_id, t2.user_id, t1.group_id
from your_table t1
join your_table t2
on t1.user_id < t2.user_id
and t1.group_id = t2.group_id;

答案 1 :(得分:1)

您不需要“多个WHERE子句”,甚至不需要自我加入:

SELECT group_id
FROM theTable AS t
WHERE t.user_id IN (1, 3)
GROUP BY group_id
HAVING COUNT(DISTINCT user_id) = 2;

更一般地说

SELECT group_id
FROM theTable AS t
WHERE t.user_id IN ([user id list])
GROUP BY group_id
HAVING COUNT(DISTINCT user_id) = [# of user ids in list];

编辑:哦,你想要团体数量......

SELECT COUNT(1) FROM (
  SELECT group_id
  FROM theTable AS t
  WHERE t.user_id IN (1, 3)
  GROUP BY group_id
  HAVING COUNT(DISTINCT user_id) = 2
);

答案 2 :(得分:0)

尝试连接同一个表的两个实例(对于每个实例,只选择相对于其中一个用户的记录),使用group_id作为连接属性,并计算结果:

SELECT COUNT(*)
FROM table AS t1
JOIN table AS t2 ON t1.group_id=t2.group_id
WHERE t1.user_id=1 AND t2.user_id=3;

答案 3 :(得分:0)

SELECT COUNT(*)
FROM   TABLE_NAME USER_ONE_INFO
       TABLE_NAME USER_TWO_INFO
WHERE  USER_ONE_INFO.ID = USER_ONE_ID
AND    USER_TWO_INFO.ID = USER_TWO_ID
AND    USER_ONE_INFO.GROUP_ID = USER_TWO_INFO.GROUP_ID;