我有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
)
我可以修改我的查询,还是需要左联接的其他类型的查询?
答案 0 :(得分:1)
您需要的是加入
Select * from answers left join question on answers.question_id = question.id;
答案 1 :(得分: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