SQL LEFT JOIN with WHERE statement after is not displaying unconnected rows

DelB95 :

I’m trying to return all of the course_codes from my curriculum table while also displaying a specific student’s progress in each course. The transcript table holds all the courses the student has taken or is taking and has their grade is those courses. When I use the below code, I almost get the output I’m looking for (All courses codes in the curriculum and the student’s grade from the transcript table if they have taken a course that is in the curriculum. The courses the student hasn’t taken yet should display an output of null in any field from the transcript table). But I need to return the grades for a specific student and not all of the students. The query below does not take that into account.

SELECT DISTINCT curriculum.Course_Code, transcript.Course_Grade, transcript.Course_Comp, transcript.CWID 
FROM curriculum 
LEFT JOIN transcript 
ON curriculum.Course_Code = transcript.Course_Code ;

Result: Query with no WHERE

The next query is the same as the one above but tries to return the grades for a specific student by adding WHERE transcript.CWID = “C38475920”. The output of the query is only the class that are in both the student’s transcript and curriculum.

SELECT DISTINCT curriculum.Course_Code, transcript.Course_Grade, transcript.Course_Comp, transcript.CWID 
FROM curriculum 
LEFT JOIN transcript 
ON curriculum.Course_Code = transcript.Course_Code 
WHERE transcript.CWID = "C38475920";

Result: Query with WHERE

How can I get a result of all the course_codes from the curriculum and a student’s grades in those courses with a CWID of "C38475920"?

Example: If a student with a transcript.CWID of “C38475920" has completed 5 courses in the curriculum and there are a total of 10 courses in the curriculum. All 10 course_codes in the curriculum will be returned with 5 courses that the student has taken showing grade values and 5 courses the student hasn’t taken yet showing NULL values in transcript.COURSE_GRADE, transcript.COURSE_COMP, etc…

GMB :

Just move the condition on the left joined table from the where clause to the on part of the join:

SELECT ...
FROM curriculum c
LEFT JOIN transcript t 
    ON c.Course_Code = t.Course_Code and t.CWID = "C38475920";

Conditions in the where clause are mandatory, so the way you phrased the query actually turned the left join to an inner join: if a curriculum had no transcript, the where clause evicts the corresponding row.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401658&siteId=1
Recommended