Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining these two specific tables

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

like image 673
Dite Gashi Avatar asked May 03 '13 18:05

Dite Gashi


4 Answers

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
like image 56
codingbiz Avatar answered Sep 25 '22 21:09

codingbiz


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
like image 42
Explosion Pills Avatar answered Sep 23 '22 21:09

Explosion Pills


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;
like image 45
cdhowie Avatar answered Sep 23 '22 21:09

cdhowie


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

like image 43
Vivek Sadh Avatar answered Sep 23 '22 21:09

Vivek Sadh