我有一个看起来像这样的表:
Teacher | Class | Number of students
Ms. Smith | 101 | 101
Mr. Frank | 300 | 20
Mr. Frank | 401 | 0
Mr. Smith | 102 | 20
Ms. Date | 300 | 0
Mr. First | 100 | 10
我想查询并找回一张已删除任何教师(他们所有的行)的表,这些教师的班级为零,所以我要找的结果是:
Teacher | Class | Number of students
Ms. Smith | 101 | 101
Mr. Smith | 102 | 20
Mr. First | 100 | 10
知道我怎么能这样做吗?我很难过。
答案 0 :(得分:3)
使用not exists
:
select *
from teachers t
where not exists (
select 1
from teachers
where number_of_students = 0 and teacher = t.teacher)
teacher | class | number_of_students
-----------+-------+--------------------
Ms. Smith | 101 | 101
Mr. Smith | 102 | 20
Mr. First | 100 | 10
(3 rows)
答案 1 :(得分:1)
如果您不能使用子查询:
SELECT t1.Teacher, t1.Class, t1.number_of_students
FROM yourTable t1
LEFT JOIN yourTable t2
ON t1.teacher = t2.teacher
AND t2.number_of_students = 0
WHERE t2.teacher IS NULL
答案 2 :(得分:1)
您的表格未正常化。您别无选择,只能使用教师姓名。如果有同名教师,这将是一个问题,但这是你如何做到的:
SELECT *
FROM teachers t1
WHERE t1.teacher NOT IN (SELECT t2.teacher
FROM teachers t2
WHERE t2.teacher = t1.teacher
AND number_of_students = 0)
或者可能更简单的方法:
SELECT *
FROM teachers t1
WHERE (SELECT COUNT(*)
FROM teachers t2
WHERE t2.teacher = t1.teacher
AND number_of_students = 0) > 0
或者你可以使用Klin稍微好一点的答案。