2015-02-08 119 views
1

我有一个表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 

回答

0
SELECT * 
FROM student_course 
WHERE course = 'a' 
AND student NOT IN (SELECT student 
        FROM student_course 
        WHERE course = 'b'); 
+0

仅供参考''时返回subquery'一个'NULL'值 – 2015-02-08 07:31:36

0
SELECT * FROM student_course 
WHERE course = 'a' AND student NOT IN 
(
SELECT student FROM student_course a 
WHERE course = 'b' 
) 
+0

这将返回有“A”的所有行不In'会失败,因为它不是“B”,并为所有的真实一排上。 – 2015-02-08 07:23:09

+0

已更新的答案。 – 2015-02-08 07:33:35

0
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 
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') 
0

使用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 
0
select * from student_course 
where course = 'a' and student not in (select student from student_course where course = 'b')