MySQL的 - 选择不包含特定值的所有唯一的记录

问题描述 投票:1回答:2

(很抱歉,如果问题已经被问过或过于简单)

从表中选择学生的所有独特的名称,其中级别=“高中”,并没有运动(“足球”,“篮球”)科目。

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

我试着用“存在”是这样的:

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
mysql sql select distinct exists
2个回答
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所有记录都超过'Soccer''Basketball'不同的主题,这是假的,导致没有结果由外查询返回。

demo on Db Fiddle与样本数据得出:

| name   | level       |
| ------ | ----------- |
| Andrea | High school |
| Susan  | High school |

0
投票

请试试这个。

SELECT DISTINCT ID, name, level FROM Students WHERE level = 'High school' AND  subject NOT IN ('Soccer', 'Basketball') ;
© www.soinside.com 2019 - 2024. All rights reserved.