我有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