1

I have 2 tables, one called course and another called course_tutor_link. I am trying to get a list of all the courses that a tutor is not subscribed to. This would be a simple left join but because at the start I will have courses that have no tutors attached to them this seems to mess up the code, so far I have:

SELECT  c.course_id, c.course,
users_id
FROM course AS c
LEFT JOIN course_tutor_link AS ctl
USING (course_id)
GROUP BY course_id

This will give me all of the courses including the ones that the user is subscribed to (about 11 rows), as soon as I try and do a filter with the users_id I automatically also lose all of the courses that have no tutor attached eg.

SELECT c.course_id, c.course 
FROM course AS c
JOIN course_tutor_link AS ctl
USING (course_id)
WHERE users_id !=9

It drops down to just the courses I have tutors subscribed to. looking through SO I noticed the use of sub-queries and not exist but I just can't get the correct syntax, all I get is no rows returned, the query I have is:

SELECT  c.course_id, c.course,
users_id
FROM course AS c
LEFT JOIN course_tutor_link AS ctl
USING (course_id)
WHERE NOT EXISTS (SELECT course_id FROM course_tutor_link WHERE users_id = 9)

I'm obviously doing something stupid but I don't know what

regards

Zen

2
  • Your second code sample seems to be identical to the first. Commented Dec 30, 2013 at 0:25
  • sorry got code blindness, updated Commented Dec 30, 2013 at 8:27

2 Answers 2

1
SELECT c.course_id, c.course
FROM course AS c
    LEFT JOIN course_tutor_link AS ctl 
        ON c.course_id=ctl.course_id AND ctl.user_id=9
WHERE ctl.course_id IS NULL
Sign up to request clarification or add additional context in comments.

2 Comments

Doh! talk about a brain fart. It works perfectly thanks toph and as I understand it more efficient than the subquery method that I was asking for and you have given below?, I completely forgot about the obvious IS NULL and had tried course_is=NULL which doesn't work
My two answers are correct. The better one depends of your data.You should try both against filled tables and choose the faster one.
0

or

SELECT course_id, course
FROM course
WHERE course_id NOT IN (SELECT course_id FROM course_tutor_link WHERE users_id=9)

1 Comment

I believe it will be better if in the future you add 2nd (3rd, etc.) solution(s) to the same answer (edit) instead of creating new ones.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.