2016-09-08 114 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 IS NULL'或'AND q.free IS NULL'? –

+0

@KenWhite好吧,我已經測試過它,並且是[它工作](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或文本,即使它們之間存在空白或「」之間的差異 – deW1

相關問題