行不返回NULL

时间:2013-11-08 20:14:15

标签: sql oracle null left-join

我正在尝试选择学生以及其中每一个已注册的学生。因此,如果学生在任何课程中都没有注册我想要显示0或没有。在我能做到这一点之前,我想让行返回null,但它没有发生。它给了我正确的结果,除了我没有一行为null。

SELECT s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE, COUNT(*) AS ENROLLED
FROM STUDENT s,ENROLLMENT e, SECTION z
WHERE s.STUDENT_ID = e.STUDENT_ID
AND e.SECTION_ID = z.SECTION_ID
AND s.PHONE LIKE '702%'
GROUP BY s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE

所以如果它确实为没有注册任何课程的学生返回null我想做这样的事情

SELECT lt.STUDENT_ID,lt.FIRST_NAME, lt.LAST_NAME, NVL(COUNT(ENROLLED), 0) AS ENROLLED
FROM STUDENT lt
LEFT OUTER JOIN
(SELECT s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE, COUNT(*) AS ENROLLED
FROM STUDENT s,ENROLLMENT e, SECTION z
WHERE s.STUDENT_ID = e.STUDENT_ID
AND e.SECTION_ID = z.SECTION_ID
AND s.PHONE LIKE '702%'
GROUP BY s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE) rt
ON lt.STUDENT_ID = rt.STUDENT_ID
GROUP BY lt.STUDENT_ID,lt.FIRST_NAME, lt.LAST_NAME;

如何获取返回null的行?

1 个答案:

答案 0 :(得分:3)

使用LEFT [OUTER] JOIN

SELECT s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE, COUNT(*) AS ENROLLED
FROM   STUDENT         s
LEFT   JOIN ENROLLMENT e ON e.STUDENT_ID = s.STUDENT_ID 
LEFT   JOIN SECTION    z ON z.SECTION_ID = e.SECTION_ID
WHERE  s.PHONE LIKE '702%'
GROUP  BY s.STUDENT_ID, z.COURSE_NO, e.ENROLL_DATE

Details in the language reference.