SQL:在至少与一个特定人员相同的俱乐部中查找人员的姓名

时间:2015-03-22 04:20:10

标签: sql

我有这张桌子:俱乐部(俱乐部名称,会员名称)

photography | Jim
photography | Eve
photography | Alex
woodworking | Jim
woodworking | Alex
cooking     | Alex

如何找到与Jim至少在同一个俱乐部的人的姓名?

在这个例子中,我想要回复Alex。


我知道如何在Jim的任何一个俱乐部中找到人的名字

SELECT DISTINCT C1.membername
FROM clubname C1, clubname C2
WHERE C1.clubname = C2.clubname AND C2.membername = 'Jim" AND C1.membername <> 'Jim'

但是,我如何指定我只想要与Jim在同一个俱乐部中的人?

4 个答案:

答案 0 :(得分:1)

我一直在寻找类似于设定差异运算符的解决方案,它基本上是PM 77-1发布的链接。

这就是我最终得到的结果:

SELECT membername
FROM club
WHERE clubname NOT IN (
    SELECT C.clubname
    FROM club C
    WHERE C.clubname NOT IN (
        SELECT clubname
        FROM club
        WHERE membername = 'Jim'
    )
)
AND membername <> 'Jim'
GROUP BY membername
HAVING COUNT(membername) = (
    SELECT COUNT(*)
    FROM club
    WHERE membername = 'Jim'
)

感谢您的帮助。

答案 1 :(得分:0)

如果您的俱乐部少于32个,请为每个俱乐部分配一个二进制标志值:

photography     1
cooking         2
woodworking     4
etc..  8, 16, 32, 64, 128, 256....

然后求和Jim并计算其成员资格并检查所有Jim的位是否都设置在该值中(使用按位AND)

答案 2 :(得分:0)

您可以通过多种方式执行此操作,一种方法是使用where not exists,如下所示:

SELECT DISTINCT C1.membername
FROM club C1 
WHERE NOT EXISTS (
    SELECT C2.membername
    FROM club C2 LEFT OUTER JOIN club C3 ON C2.clubname=C3.clubname 
    AND C3.membername=C1.membername
    WHERE C2.membername = 'Jim' AND C3.membername IS NULL
)
AND C1.membername !=  'Jim'

刚刚使用T-SQL here is the DEMO尝试了它。

答案 3 :(得分:0)

蛮力解决方案:

SELECT DISTINCT c1.membername
FROM Club c1 
WHERE c1.membername <> 'JIM' AND NOT EXISTS 
               (SELECT 1 FROM Club WHERE membername = 'JIM' AND  clubname NOT IN
                     (SELECT clubname FROM Club c2 WHERE c2.membername = c1.membername)
                 );

SQL Fiddle Demo (based on SQL Server)

相同的代码适用于大多数其他RDBMS,因为它只使用标准语法。