我有這樣的表結構:如何選擇所有相關帖子?
// qanda
+----+----------------------------------------+---------+-----------+------+
| Id | body | related | user_id | free |
+----+----------------------------------------+---------+-----------+------+
| 1 | content of question1 | null | 2 | null |
| 2 | content of first answer for question1 | 1 | 2 | null |
| 3 | content of question2 | null | 6 | 300 |
| 4 | content of second answer for question1 | 1 | 4 | null |
| 5 | content of first answer for question2 | 3 | 2 | null |
| 6 | content of question3 | NULL | 8 | null |
| 7 | content of first answer for question3 | 6 | 4 | null |
| 8 | content of second answer for question3 | 6 | 2 | null |
+----+----------------------------------------+---------+-----------+------+
/* related column: it is NULL for questions, and the id of its own question for answers.
free column: Actually that's just for questions. NULL means it is a free question
and any number else means it isn't. (answers always are NULL) */
我需要選擇屬於自由問題用戶的所有答案。例如,我想選擇該用戶的所有答案:$user = 2
。所以這是預期的結果:
+----+----------------------------------------+---------+-----------+------+
| Id | body | related | user_id | free |
+----+----------------------------------------+---------+-----------+------+
| 2 | content of first answer for question1 | 1 | 2 | null |
| 8 | content of second answer for question3 | 6 | 2 | null |
+----+----------------------------------------+---------+-----------+------+
我該怎麼做?
SELECT a.*
FROM qanda q
JOIN qanda a
ON q.id = a.related
WHERE related IS NOT NULL -- this specifics answers
AND user_id = 2
AND ...
出了什麼問題'和a.free IS NULL'或'AND q.free IS NULL'? –
@KenWhite好吧,我已經測試過它,並且是[它工作](http://sqlfiddle.com/#!9/81151/3)。謝謝。 –