Reputation: 83
I have a question about MySQL table.
I have 2 tables (users (user_id and other rows) and answers (id, answer_id and user_id))
I would like to check, which questions the user hasn't answered (for example, in answers table exists 5 rows - 4,6,8,1,3 (but questions are 10), I would like to get out from database values 2,5,7,9,10).
How to write a query like this? I've tried with JOIN, but nothing was successful at all!
Upvotes: 5
Views: 1949
Reputation: 15399
I suppose you've got a QUESTION
table:
select *
from question
where not exists(
select 'x'
from answer
where answer.question_id = question.id
)
If you haven't got a QUESTION
table, IMHO there's no solution
Upvotes: 3
Reputation: 519
Or use LEFT JOIN, it's faster.
SELECT q.id
FROM question q
LEFT JOIN answers a
ON a.question_id = q.id
WHERE a.id IS NULL
Upvotes: 3
Reputation: 3778
Assuming that you have a questions and an answers table, this is the standard TSQL solution:
SELECT Q.QUESTION_ID
FROM QUESTIONS Q LEFT JOIN ANSWERS A ON Q.QUESTION_ID = A.QUESTION_ID
WHERE A.QUESTION_ID IS NULL
Upvotes: 5
Reputation: 1013
not sitting in front of a mySQL DB but it should be something to the point of (you didn't tell us where your questions are listed so I put in a placeholder) It also seems like your answer table HAS to have or should have a link to the question_id it is answering. If I made any incorrect assumptions please let me know and I will edit as needed.
Select question_id from question_table
where question_id not in (select question_id from answers)
Upvotes: 3