我有一个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

最佳答案

我想你需要这样的东西:

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
伊迪丝2:现在我完全明白你在找什么了。这将为您提供正确的结果:
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修改group by,并使用SELECT distinct your_table.mid修改您的选择。

关于php - 验证组中特定且唯一的一组值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13593234/

10-16 13:20