我有一个具有以下结构的MySQL表:
我想要一个查询,它会收到一组uid
s(或单个uid
),然后检查它们是否存在于特定中间的封闭组中。如果它们存在,则查询应返回它们所在的mid
。例如,在上表中:
('chuks.obima', 'crackhead') should return '2
('vweetah','crackhead') should return '1'
('vweetah','crackhead','chuks.obima') should return 3
('crackhead') should return an empty result
答案 0 :(得分:4)
我认为你需要这样的东西:
SELECT mid
FROM your_table
WHERE uid in ('favour','crackhead','charisma')
GROUP BY mid
HAVING COUNT(*)=3
编辑:根据您的第二个示例,这就是您要寻找的内容:
SELECT mid
FROM your_table
WHERE uid in ('vweetah', 'crackhead')
GROUP BY mid
HAVING
COUNT(distinct uid)=
(select count(*)
from (select 'vweetah' union select 'crackhead') s)
或者您可以使用您要查找的元素数替换最后一个子查询,例如HAVING COUNT(distinct uid) = 2
EDIT2 :现在我完全理解你在寻找什么。这应该会给你正确的结果:
SELECT your_table.mid, s.tot_count, count(distinct uid)
FROM
your_table inner join
(select mid, seq, count(distinct uid) tot_count from your_table group by mid, seq) s
on your_table.mid = s.mid and your_table.seq=s.seq
WHERE your_table.uid in ('crackhead')
GROUP BY your_table.mid
HAVING COUNT(distinct uid)=s.tot_count AND COUNT(distinct uid)=1
其中最后一次计数等于您要查找的元素数。这可以简化为:
SELECT your_table.mid
FROM your_table
GROUP BY your_table.mid
HAVING
count(distinct uid)=
count(distinct case when your_table.uid in ('vweetah','crackhead','chuks.obima') then your_table.uid end)
and count(distinct uid)=3
如果所有uid都在同一个seq
下,系统会被视为已关闭,则您还必须使用以下代码修改分组:group by your_table.mid, your_table.seq
,并选择SELECT distinct your_table.mid
答案 1 :(得分:2)
要验证它是否为封闭组,您可以获取该COUNT()
组的所有成员的汇总mid
,并将其与列表中的人数进行比较。如果它们相等,它就会被关闭。
如果所有3人都在群组中,则以下将返回1
,并且该群组中的总人数也为3。
SELECT
(((SELECT COUNT(*) FROM yourtable WHERE `uid` IN ('favour','crackhead','charisma') AND `mid` = 2)
=
(SELECT COUNT(*) FROM yourtable WHERE `mid` = 2))
AND (SELECT COUNT(*) FROM yourtable WHERE `mid` = 2) = 3) AS group_is_closed
将其包装在子查询中以避免计算mid
两次。
SELECT
/* 3 is the number of uid you are looking for */
(mid_count = 3 AND mid_count = member_count) AS group_is_closed
FROM (
SELECT
/* Find how many of your uids are in the `mid` */
(SELECT COUNT(*) FROM yourtable WHERE `uid` IN ('favour','crackhead','charisma') AND `mid` = 2) AS member_count,
/* Find the total number of uids in the `mid` */
(SELECT COUNT(*) FROM yourtable WHERE `mid` = 2) AS mid_count
) subq
mid
,返回1)mid
中,返回0)答案 2 :(得分:2)
试试这个:
SELECT mid
FROM your_table
WHERE uid in ('favour','crackhead','charisma')
GROUP BY mid
HAVING COUNT(DISTINCT uid) = 3