我有一個表student_course如下基於條件的表: -查找記錄使用SQL
student course
1 a
2 a
1 b
4 a
5 d
2 d
5 a
我需要找到所有的行,其中當然=一和當然不是在B。結果應該是: -
student course
2 a
4 a
5 a
我有一個表student_course如下基於條件的表: -查找記錄使用SQL
student course
1 a
2 a
1 b
4 a
5 d
2 d
5 a
我需要找到所有的行,其中當然=一和當然不是在B。結果應該是: -
student course
2 a
4 a
5 a
SELECT *
FROM student_course
WHERE course = 'a'
AND student NOT IN (SELECT student
FROM student_course
WHERE course = 'b');
SELECT * FROM student_course
WHERE course = 'a' AND student NOT IN
(
SELECT student FROM student_course a
WHERE course = 'b'
)
這將返回有「A」的所有行不In'會失敗,因爲它不是「B」,併爲所有的真實一排上。 – 2015-02-08 07:23:09
已更新的答案。 – 2015-02-08 07:33:35
select student
from student_course
group by student
having sum(case when course = 'a' then 1 else 0 end) > 0
and sum(case when course = 'b' then 1 else 0 end) = 0
嘗試此查詢:
SELECT ca.Student, ca.Course
FROM student_course ca
WHERE ca.course = 'a'
AND NOT EXISTS (SELECT 1 FROM student_course cb
WHERE ca.Student = cb.Student AND cb.course = 'b')
使用LEFT JOIN
。
SELECT T1.*
FROM student_course T1
LEFT JOIN student_course T2 ON T1.student = T2.student AND T2.course = 'B'
WHERE T1.course = 'A' AND T2.student IS NULL
select * from student_course
where course = 'a' and student not in (select student from student_course where course = 'b')
僅供參考''時返回subquery'一個'NULL'值 – 2015-02-08 07:31:36