Tediee
Tediee

Reputation: 83

Check what values doesn't exist in SQL database

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

Answers (4)

Joe Taras
Joe Taras

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

Ziouas
Ziouas

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

kiks73
kiks73

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

Talspaugh27
Talspaugh27

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

Related Questions