如何 select 不存在多个值的行

How to select rows where multiple values do not exist

场景:查理、艾米和罗伯特各自填写了一份调查问卷,要求用户select他们感兴趣的所有运动。问题是多项选择。在 table surveyData 中,每一行代表每个用户选择的一个答案。所以 Charlie(0001) 选择了 basketballrugbyacrobaticsdarts.

我想select从table所有surveyDataIds (users)身上选出恰好basketball (0002)rugby (0003)。我相信我在这里要做的是执行 NAND 类型的操作。

期望的结果:当查询此 table 时,我希望 return 以下 surveyDataIds00020004surveyDataIds 需要分组以防止重复。罗伯特 return 不像他 select 那样 basketball (0002)

这是我到目前为止尝试过的方法,并从 post 中的答案中获取建议。不幸的是,它不起作用并且 return 得到了错误的结果。

select *
FROM surveyData sd
WHERE NOT EXISTS (
    SELECT 1
    FROM surveyData sd2
    WHERE sd.surveyDataId = sd2.surveyDataId AND sd.chosenInterests in (2, 3)
)

0001 = Charlie
0002 = Amy
0003 = Robert
0004 = Lauren

interest options
0 = tennis
1 = football  
2 = basketball
3 = rugby  
4 = snooker  
5 = acrobatics 
6 = bowling 
7 = squash  
8 = cricket 
9 = darts   
10 = javelin

Table 姓名:surveyData

surveyDataId chosenInterests
0001 2
0001 3
0001 5
0001 9
0002 6
0002 7
0002 9
0002 1
0002 4
0002 8
0003 2
0003 7
0004 10

使用 NOT IN:

select distinct surveyDataId
FROM surveyData
WHERE surveyDataId NOT IN (
    SELECT surveyDataId
    FROM surveyData
    WHERE chosenInterests in (2,3)
);

顺便说一下,您使用 EXISTS 的查询也可以:

select distinct surveyDataId
FROM surveyData sd1
WHERE NOT EXISTS (
    SELECT *
    FROM surveyData sd2
    WHERE sd1.surveyDataId = sd2.surveyDataId and chosenInterests in (2,3)
);

我相信你只是用错了别名:

select distinct surveydataid
from surveydata sd
where not exists (
    select *
    from surveydata sd2
    where sd2.surveydataid=sd.surveydataid 
      and sd2.choseninterests in (2,3)
)