2

我有一个具有以下结构的 MySQL 表:

在此处输入图像描述

我想要一个接收一组uids (或单个 s 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
4

3 回答 3

4

I think you need something like this:

SELECT mid
FROM your_table
WHERE uid in ('favour','crackhead','charisma')
GROUP BY mid
HAVING COUNT(*)=3

EDIT: based on your second example, this is what you are looking for:

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)

or you can just substitute last subquery with the number of elements you are looking for, e.g. HAVING COUNT(distinct uid) = 2

EDIT2: now i understand exactly what you are looking for. This should give you the correct results:

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

where the last count is equal to the number of elements you are looking for. This could be simplified like this:

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 with:group by your_table.mid, your_table.seq和您的 select withSELECT distinct your_table.mid

于 2012-11-27T22:39:52.723 回答
2

要验证它是否是一个封闭组,您可以获取该组COUNT()的总成员总数mid,并将其与列表中的人数进行比较。如果它们相等,则它是封闭的。

如果所有 3 人都在组中,则以下将返回 a 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

SQLFiddle demos (aka wow, it actually works):

于 2012-11-27T21:25:45.787 回答
2

试试这个:

SELECT mid
FROM your_table
WHERE uid in ('favour','crackhead','charisma')
GROUP BY mid
HAVING COUNT(DISTINCT uid) = 3
于 2012-12-09T07:24:30.990 回答