I have 2 tables where one is a related table and the other is a base table. First one is class_has_student and the other is student. I need to return all related data of classes for a particular student in class_has_student and class information for classes where student not registered even. (student.id references class_has_student.student_id)
class_has_student table student table
class_id | student_id id | name
---------|----------- --------|---------
1| 1001 1001| John
2| 1001 1002| Michael
1| 1002 1003| Anne
3| 1002
1| 1003
2| 1003
3| 1003
4| 1003
I need to get information from class_has_student when I pass a student.id and class_has_student.class_id for related data and null for class_has_student.class_id if the student not registered to that class. For example if I want to get class registration information for John for classes 1, 2 and 3. The result I expect is related class student data for classes 1 and 2 and only class information for class 3(class table is not showed here, so returning id is sufficient). So, the result must be,
class_id | student_id
---------|-----------
1| 1001
2| 1001
3| NULL
I tried to achieve this through following query and several variations but did not succeed. It's highly appreciated if somebody could help.
SELECT chs.class_id, s.id
FROM student s LEFT OUTER JOIN class_has_student chs ON s.id = chs.student_id AND s.id = 1001
WHERE chs.class_id IN(1,2,3);
The fiddle is here. http://sqlfiddle.com/#!9/839fe/4