Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LEFT JOIN returning empty result set

I'm having a small logic issue with joins. I have a database for answering answer. The schema is:

Question
question_id
question_text

Answers
answer_id
question_id
answer_text

User Responses
user_id
answer_id
question_id

I am trying to find questions that a user has not already answered but I keep getting null responses. The query is below:

SELECT * FROM questions 
    LEFT JOIN responses ON questions.question_id = responses.question_id 
WHERE user_id != '1'

Where did my logic go wrong?

like image 764
Devin Dixon Avatar asked Aug 31 '26 21:08

Devin Dixon


1 Answers

Try a LEFT JOIN with IS NULL

SELECT q.question_id FROM questions q
    LEFT JOIN responses r ON q.question_id = r.question_id AND r.user_id = 1
WHERE r.question_id IS NULL
like image 149
liquorvicar Avatar answered Sep 03 '26 14:09

liquorvicar