MySQL - Select 所有不包含特定值的唯一记录
MySQL - Select all unique records that do not contain certain values
(抱歉,如果问题已经被问过或者太简单了)
Select 来自 table 水平 = 'High school' 且没有体育('Soccer'、'Basketball')科目的学生的所有唯一姓名.
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
您需要使用 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'
不同的主题,即false,导致外部查询没有返回任何结果。
这个 demo on Db Fiddle 与您的样本数据产量:
| name | level |
| ------ | ----------- |
| Andrea | High school |
| Susan | High school |
请试试这个。
SELECT DISTINCT ID, name, level FROM Students WHERE level = 'High school' AND subject NOT IN ('Soccer', 'Basketball') ;
(抱歉,如果问题已经被问过或者太简单了)
Select 来自 table 水平 = 'High school' 且没有体育('Soccer'、'Basketball')科目的学生的所有唯一姓名.
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
您需要使用 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'
不同的主题,即false,导致外部查询没有返回任何结果。
这个 demo on Db Fiddle 与您的样本数据产量:
| name | level |
| ------ | ----------- |
| Andrea | High school |
| Susan | High school |
请试试这个。
SELECT DISTINCT ID, name, level FROM Students WHERE level = 'High school' AND subject NOT IN ('Soccer', 'Basketball') ;