2016-09-08 8 views
0

私はこのテーブルの構造を持っている:どのように関連記事をすべて選択できますか?

// 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 ... 
+0

何 'と間違っているとa.freeはNULL'または'とq.freeがNULL'ですか? –

+0

@KenWhite [OK]私はそれをテストしたし、[それは動作します](http://sqlfiddle.com/#!9/81151/3)。ありがとうございました。 –

答えて

1
-- Working Query 
SELECT 
    answer.* 
FROM 
    qanda question 
     JOIN 
    qanda answer ON question.Id = answer.related 
WHERE 
    answer.related IS NOT NULL 
     AND answer.user_id = 2 
     AND question.free IS NULL; 

私は、クエリを少し明確にするために、私のテスト中にビットを命名変更の自由を取りました。

あなたが空に実際関連する質問の状態をチェックしていなかったので、あなたがそのユーザーの別のレコードを得ているだろう前にあなたが持っていたクエリでAND question.free IS NULL

を欠落していました。

私は別のデータベース設計を考えていますが、私がよく知っているように、それは必ずしも可能ではありません。

Working example

-3

次のクエリを使用できます。

SELECT * FROM qanda WHERE user_id=2 AND free="" AND related IS NOT NULL; 
+0

これは関連する質問を全くチェックせず、 'related'がvarcharやtextでない可能性が高いため結果を返しません。 – deW1

関連する問題