Here is my table structure:
// questions_and_answers
+----+-------------------+------+----------+
| id | body | type | related |
+----+-------------------+------+----------+
| 1 | a question | 0 | NULL |
| 2 | my answer | 1 | 1 |
| 3 | another answer | 1 | 1 |
| 4 | another question | 0 | NULL |
| 5 | another answer | 1 | 4 |
| 6 | another answer | 1 | 1 |
+----+-------------------+------+----------+
-- type column: it is either 0 for questions and 1 for answers.
-- related column: it is either null for questions and "the id of its question" for answers
Now I need to select all unanswered questions. Here is my query:
SELECT *
FROM questions_and_answers AS qa
WHERE
type = 0 -- just questions
AND
qa.id NOT IN (SELECT q.related FROM qanda q WHERE q.type <> 0) -- unanswered ones
It works well and all fine.
What's my question? My query matches no row when there is a row like this:
| 7 | another answer | 1 | NULL |
See? the value of type
is 1
, so it is an answer. But the value of related
is NULL
, so it doesn't point to any question. In general that row makes no sense, but probably sometimes happens (when a question is removed and we set the related
of its answers to null
). In this case, the result of my query is "no row selected".
Why? And how can I make my query safe against such a situation? (safe == ignore them and still match unanswered questions)