I have encountered a interesting problem today (or so it seems to me) and I thought it would be productive to share it.
I have two database tables with the following construct:
Table 1: mod_class
class_id
CSD2311
CSD2314
CSD12
Table 2: m_classes_enrolled_in
student_id class_id
5 CSD2311
5 CSD2314
So the first table has all possible class_id's and the second one has class_id's and the student that is enrolled in that class. I would like to create a list of all classes that the student is not enrolled in. So far a left-join looked really nice but it seems impossible to display it in this way:
SELECT mod_enrolled_in.class_id
FROM mod_enrolled_in
WHERE student_id <> 5
INNER JOIN mod_class
ON mod_enrolled_in.class_id = mod_class.class_id
Any help would be greatly appreciated, -D
You could do that several ways
1)
Select class_id from mod_class
EXCEPT
Select class_id From m_classes_enrolled_in WHERE student_id = 5
2)
Select class_id from mod_class
Where class_id NOT IN
(Select class_id From m_classes_enrolled_in WHERE student_id = 5)
3)
Select class_id from mod_class m
LEFT JOIN
(Select class_id From m_classes_enrolled_in WHERE student_id = 5) cs
ON m.class_id = cs.class_id
WHERE cs.class_id IS NULL
Don't you want to LEFT JOIN
mod_class
so you can do an anti-join?
SELECT mod_class.class_id
FROM mod_class
LEFT JOIN mod_enrolled_in ON (mod_class.class_id = mod_enrolled_in.class_id
AND mod_enrolled_in.student_id = 5)
WHERE mod_enrolled_in.class_id IS NULL
Try this:
SELECT c.class_id
FROM mod_class c
LEFT OUTER JOIN mod_enrolled_in e
ON e.class_id = c.class_id
AND e.student_id = ?
WHERE e.student_id IS NULL;
Use this:-
Select class_id from mod_class
Where class_id NOT IN (Select class_id From m_classes_enrolled_in)
See this SQL FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With