(很抱歉,如果之前提出过问题或过于简单)
从表中选择所有唯一的名称,这些学生的等级=“高中”且没有运动(“足球”,“篮球”)科目。
ID name level subject
00001 John High school Science
00002 John High school Math
00003 John High school *Soccer*
00004 John High school English
00005 Andrea High school Math
00006 Andrea High school Science
00007 Andrea High school English
00008 Susan High school History
00009 Susan High school English
00010 Susan High school Math
00011 Michael High school Since
00012 Michael High school Math
00013 Michael High school *Basketball*
00014 Michael High school English
00015 Mary Middle school Math
我尝试这样使用'EXISTS':
SELECT ID, name, level FROM Students WHERE level = 'High school' AN NOT EXISTS(
SELECT * FROM Students WHERE subject IN ('Soccer', 'Basketball') );
结果应为:
Andrea High school
Susan High school
答案 0 :(得分:1)
您需要使用name
列将子查询与外部查询进行关联:
SELECT DISTINCT s.name, s.level
FROM students s
WHERE s.level = 'High school'
AND NOT EXISTS (
SELECT 1 FROM students s1 WHERE s1.name = s.name AND s1.subject IN ('Soccer', 'Basketball')
)
没有相关性,子查询实际上检查students
中的 all 条记录是否具有与'Soccer'
和'Basketball'
不同的主题,这是错误的,导致没有结果由外部查询返回。
此 demo on Db Fiddle 和您的示例数据可得出:
| name | level |
| ------ | ----------- |
| Andrea | High school |
| Susan | High school |
答案 1 :(得分:0)
请尝试这个。
SELECT DISTINCT ID, name, level FROM Students WHERE level = 'High school' AND subject NOT IN ('Soccer', 'Basketball') ;