想到我自己学习SQL并开始使用
我正在练习一些教程并陷入一个基本查询。
在尝试了很多次后,我无法让它运行。
问题是:在哪些年份获得了物理奖,但没有获得化学奖。
这是我试过的
SELECT yr
FROM nobel
WHERE subject ='Physics' AND
NOT (Select yr from nobel where subject = 'Chemistry')
有人可以提供帮助。
答案 0 :(得分:4)
SELECT yr
FROM nobel
WHERE subject ='Physics' AND
yr NOT IN (Select yr from nobel where subject = 'Chemistry')
答案 1 :(得分:2)
如此接近!您只需要yr
和IN
:
SELECT yr
FROM nobel
WHERE subject ='Physics' AND
yr NOT IN (Select yr from nobel where subject = 'Chemistry')
您也可以使用排除联接执行此操作:
SELECT yr
FROM nobel n1
LEFT JOIN nobel n2 ON n1.yr = n2.yr AND n2.subject = 'Chemistry'
WHERE n1.subject = 'Physics' AND n2.subject is NULL
或NOT EXISTS
SELECT yr
FROM nobel n1
WHERE n1.subject ='Physics'
AND NOT EXISTS
(
SELECT NULL
FROM nobel n2
WHERE n2.subject = 'Chemistry' AND n2.yr=n1.yr
)
答案 2 :(得分:1)
您还可以使用LEFT [OUTER] JOIN
,以确保同一年内不存在任何行:
SELECT yr
FROM nobel p
LEFT JOIN nobel c ON c.yr = p.yr
AND c.subject = 'Chemistry'
WHERE p.subject = 'Physics'
AND c.yr IS NULL;
基本上有4种技术:
答案 3 :(得分:0)
我相信你不需要第二个AND
条件;因为第二个条件,您只是想要排除yr
为subject
的所有chemistry
。您的查询可以只是
SELECT yr
FROM nobel
WHERE subject ='Physics'
答案 4 :(得分:0)
试试这个:
SELECT yr
FROM nobel
WHERE subject ='Physics' AND yr
NOT IN(Select yr from nobel where subject = 'Chemistry') GROUP BY yr desc
答案 5 :(得分:0)
省略
NOT(从诺贝尔选择主题='化学')
因为你只是在寻找以Physics为主题的行。您不需要NOT查询,因为sql查询会自动省略Chemistry。
答案 6 :(得分:0)
SELECT yr
FROM nobel
WHERE subject ='Physics' AND subject <> 'Chemistry'
------------或者您可以尝试以下---------------------------
SELECT yr
FROM nobel
WHERE subject ='Physics'
except
SELECT yr
FROM nobel
WHERE subject ='Chemistry'