2017-07-14 37 views
0

這裏是我的表結構:如何加入null?

-- qanda (stands for questions and answers) 
+----+---------+-----------------------------------------------+--------------+ 
| id | title |      content     | question_id | 
+----+---------+-----------------------------------------------+--------------+ 
| 1 | title1 | this is a question       | NULL   | 
| 2 | NULL | this is an answer        | 1   | 
| 3 | NULL | this is another answer      | 1   | 
| 4 | title2 | this is another question      | NULL   | 
| 5 | NULL | this is an answer for the second question  | 4   | 
| 6 | NULL | this is another answer for the first question | 1   | 
+----+---------+-----------------------------------------------+--------------+ 

我知道,這將是更好,如果我保持兩個不同的表中的問題和答案。但現在我只是想了解JOIN在這種情況下的工作原理。


我有一個ID爲qanda表,我總是想要一個標題。該ID可能是問題的ID或答案的ID。我怎樣才能做到這一點?


我想是這樣的:

SELECT t1.title 
FROM qanda t1 
INNER JOIN qanda t2 
ON t1.id = t2.question_id 
WHERE t1.id = :id 

我的查詢沒有匹配。這裏是預期結果的一些樣品:

-- :id = 1 
+--------+ 
| title1 | 
+--------+ 

-- :id = 2 
+--------+ 
| title1 | 
+--------+ 

-- :id = 4 
+--------+ 
| title2 | 
+--------+ 

-- :id = 5 
+--------+ 
| title2 | 
+--------+ 

-- :id = 6 
+--------+ 
| title1 | 
+--------+ 
+0

創建表格的腳本 – etsa

+0

@etsa請問您需要什麼?表格結構在我的問題中非常清楚。 –

+3

這對你來說很清楚......不適合我......如果你需要幫助,請發佈要求 – etsa

回答

1

與Serg類似;但如果您有這樣的情況,使用左連接將允許在結果中出現無結果(W/O)答案的問題。

SELECT distinct coalesce(t2.title, t1.title) as title 
FROM qanda t1 
LEFT JOIN qanda t2 
    ON t1.id = t2.question_id 
WHERE (t1.id = 1 or T2.ID = 1) 
    and Type = 0; 

如果我們可以假設一個標題只存在於問題上並且沒有答案將會有標題。

我認爲這很難維護,它應該更快,因爲它消除了連接(有點存在可以提早逃脫連接將無法和因爲限制發生在子查詢我們只有1條記錄真正處理加入)和獨特。

SELECT t1.title as title 
FROM qanda t1 
WHERE (EXISTS (SELECT 1 
       FROM qanda t2 
       WHERE ID = 1 
       and t1.ID = t2.question_id) --correlated subquery 
      or t1.id = 1) 
    and Type = 0 
+0

是否「無」表示「無」? –

+0

對不起,這是正確的。我會拼出來。 – xQbert

+0

另外,'distinct'是多餘的,因爲'id'是PK,對吧? –

3

的2聯合查詢

SELECT t1.title 
FROM qanda t1 
WHERE t1.id = :id and t1.title IS NOT NULL 
UNION 
SELECT t1.Title 
FROM qanda t2 
JOIN qanda t1 
ON t1.id = t2.question_id 
WHERE t2.id = :id 

或者

SELECT DISTINCT t1.title 
FROM qanda t1 
JOIN qanda t2 
ON t1.id = t2.question_id 
WHERE :id in (t2.id, t1.id) 
+0

是的,這是唯一的工作答案,似乎是一個沉重的查詢。不管怎麼說,還是要謝謝你。 upvote –

+0

好..我喜歡你的替代方法。你認爲哪一個更好?你的第一種方法還是第二種? –

+0

第二個應該跑的更快,只是一個猜測。 – Serg

0

你可以嘗試這樣的事情:

SELECT title 
FROM qanda 
INNER JOIN (
    SELECT DISTINCT COALESCE(t1.question_id, t1.id) AS ID 
    FROM qanda t1 
    WHERE :id IN(t1.question_id=:id, t1.id) 
    ) B ON qanda.id = B.ID; 
+0

[It does not work](http://sqlfiddle.com/#!9/cb083c/20) –

+0

你爲什麼要用'COALESCE'而不是'OR'? –

+0

答案已更新。 – etsa