tags:

views:

44

answers:

3

Is it possible to make query like this? That has some error... Query should check if user did answer question with q.id.

SELECT pictureid,
       id,
       points 
  FROM questions q 
 WHERE IF (q.id NOT IN (SELECT questions_id 
                          FROM history h 
                         WHERE h.users_id = 3))
+6  A: 
SELECT pictureid,id,points 
FROM questions q 
WHERE q.id NOT IN (
    SELECT questions_id 
    FROM history  
    WHERE users_id = 3)
RedFilter
Add AND questions_id IS NOT NULL to the subquery otherwise if there is a null it won't be correct, that is why I prefer EXISTS and NOT EXISTS
SQLMenace
+1  A: 

Yes

 SELECT pictureid,id,points 
 FROM questions q 
 WHERE q.id not in 
  (SELECT questions_id FROM history h WHERE h.users_id = 3);
tpdi
this is not valid SQL
Pavel Morshenyuk
I repeated "not in" twice. Thanks Pavel.
tpdi
+1  A: 

Using NOT EXISTS will also take care of the NULL problem with using IN

SELECT pictureid, id, points
FROM questions q
WHERE NOT EXISTS
(
    SELECT questions_id
    FROM history h
    WHERE h.questions_id = q.questions_id
    AND h.users_id = 3
)

If you want to use IN do this

SELECT pictureid, id, points
FROM questions q
WHERE q.id NOT IN
(
    SELECT questions_id
    FROM history h
    WHERE h.users_id = 3
    AND questions_id IS NOT NULL
)
SQLMenace