我有 2 个表,一个问题表和一个答案表:
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
)
我可以修改我的查询吗?或者我是否需要另一种带有左连接的查询?
最佳答案
你需要的是一个join
Select * from answers left join question on answers.question_id = question.id;
关于mysql联合还是加入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19753877/