2013-11-03 76 views
2

我有2個表,一個問題和答案的表像這樣:Mysql聯合還是加入?

question : id, title, description, date, company_id 
answers : id, question_id, answer, date, company_id 

我想要的所有問題清單詢問他們是否有答案,或者沒有,也提供所有的答案。我沒有任何麻煩,但是我不確定的部分是如何在答案數組中提供問題標題,因爲我想顯示答案與哪個問題相關。

目前我有此查詢:

SELECT id, company_id, title, description, date, \'question\' as record_type 
     FROM `questions` WHERE company_id = 9 
     UNION ALL 
     SELECT id, company_id, null as title, null as description, date, answer, question_id, \'answer\' as record_type 
     FROM `answers` WHERE company_id = 9 
     ORDER BY date ASC 

這幾乎是爲我提供了我想要的東西:

[0] => Array 
    (
     [id] => 63, 
     [company_id] => 9 
     [title] => question 1 
     [description] => test 
     [date] => 2013-08-09 20:50:19 
     [record_type] => question 
    ) 

[1] => Array 
    (
     [id] => 58 
     [company_id] => 9 
     [title] => 
     [description] => 
     [answer] => This is Bobs answer 
     [question_id] => 63 
     [date] => 2013-08-09 20:52:16 
     [record_type] => answer 
    ) 

唯一的區別是,我要交叉引用的問題表並添加問題標題的答案,以便它看起來像這樣:

[1] => Array 
    (
     [id] => 58 
     [company_id] => 9 
     [question_title] => question 1 
     [description] => 
     [answer] => This is Bobs answer 
     [question_id] => 63 
     [date] => 2013-08-09 20:52:16 
     [record_type] => answer 
    ) 

我可以修改我的查詢或我是否需要另一種帶左連接的查詢?

回答

0

如果你只想要的答案的問題的標題,並保持相同的結果集結構,你可以做一個內部聯接,因爲你的答案總是有答案:

SELECT id, company_id, title, description, date, \'question\' as record_type 
FROM `questions` WHERE company_id = 9 
UNION ALL 
SELECT a.id, a.company_id, q.title, q.description, a.date, a.answer, a.question_id, \'answer\' as record_type 
FROM `answers` a 
INNER JOIN question q ON q.id = a.question_id 
WHERE a.company_id = 9 
ORDER BY a.`date` ASC 

如果你想要得到的問題,並儘可能在同一行中的答案,你可以這樣做:

SELECT * FROM question q LEFT JOIN answers a ON a.question_id = q.question_id 
WHERE q.company_id = 9 
ORDER BY q.`date` ASC 
+0

非常好,非常感謝。第一個查詢做了我所需要的。 – 2scope

1

你需要的是一個連接

Select * from answers left join question on answers.question_id = question.id; 
+0

這很棒,它向我展示了與答案相關的問題,但我也想要所有問題,無論有沒有答案。 – 2scope

+0

然後用連接代替左連接 –