我有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
)
我可以修改我的查詢或我是否需要另一種帶左連接的查詢?
非常好,非常感謝。第一個查詢做了我所需要的。 – 2scope