私はこのテーブルの構造を持っている:どのように関連記事をすべて選択できますか?
// 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はNULL'または'とq.freeがNULL'ですか? –
@KenWhite [OK]私はそれをテストしたし、[それは動作します](http://sqlfiddle.com/#!9/81151/3)。ありがとうございました。 –