lostintheriver
lostintheriver

Reputation: 197

SQL query left join issue

I am making a query but it is not working properly.

My table details are as follows:

Subarea:
id
Fieldsofstudy

student_subarea:
id primary key,
student_id ,
student_subarea Foreign key to subarea id and the student_subarea.

ASK:
What I want to accomplish is to obtain all fields of study in one column and in another column the id of the student if he is in the class. Otherwise, show null or something.

SELECT a.`id` ,  a.`name` , a.`area_id` , u. * 
FROM  `subarea` a
LEFT JOIN student_subarea u ON u.subarea_id = a.id
WHERE u.student_id =50
OR u.student_id IS NULL

Doing this is not helping at all. I tried to use functions and subqueries without any success. Could some help me.

Upvotes: 1

Views: 57

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1269463

The general rule for left join and filtering is to put the filtering clauses in the on clause for all but the first table. So this may do what you want:

SELECT a.`id`, a.`name`, a.`area_id`, u. * 
FROM `subarea` a LEFT JOIN
     student_subarea u
     ON u.subarea_id = a.id AND u.student_id = 50;

How do you remember this logic? A left join returns all rows from the first table even when there is no match on the second table. That appears to be what you want.

The problem with your logic is that students other than student 50 match the logic. So, those rows get filtered out.

Upvotes: 2

trincot
trincot

Reputation: 349956

You should put the condition on the student ID inside the join condition, not in the where clause:

SELECT    a.id,  a.name , a.area_id, u.* 
FROM      subarea a
LEFT JOIN student_subarea u
       ON u.subarea_id = a.id
      AND u.student_id = 50

Upvotes: 0

AgRizzo
AgRizzo

Reputation: 5271

Move the filter criteria to the JOIN

SELECT a.`id` ,  a.`name` , a.`area_id` , u. * 
FROM  `subarea` a
LEFT JOIN student_subarea u 
  ON u.subarea_id = a.id
     AND u.student_id =50

Upvotes: 0

Related Questions