我有一个具有以下结构的 MySQL 表:
我想要一个查询,该查询将接收一组 uid
(或单个 uid
),然后检查它们是否存在于特定 mid 下的封闭组中。如果它们存在,查询应该返回它们所在的 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
最佳答案
我想你需要这样的东西:
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)
或者您可以将最后一个子查询替换为您要查找的元素数量,例如有计数(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
关于php - 验证组中特定且唯一的一组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13593234/