Mysql联盟还是加入?
我有两张表,一张问题表和一张答案表,如下所示:Mysql联盟还是加入?,mysql,sql,join,left-join,union,Mysql,Sql,Join,Left Join,Union,我有两张表,一张问题表和一张答案表,如下所示: question : id, title, description, date, company_id answers : id, question_id, answer, date, company_id 我想要一份所有问题的清单,询问他们是否有答案,以及提供的所有答案。我这样做没有任何问题,但我不确定的是如何在答案数组中提供问题标题,因为我想显示答案与哪个问题相关 目前我有以下问题: SELECT id, company_id, title
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
)
我可以修改我的查询吗?或者我需要另一种类型的查询,可能需要左联接吗?您需要的是联接
Select * from answers left join question on answers.question_id = question.id;
如果您只想要答案的问题标题并保持相同的结果集结构,则可以进行内部联接,因为您的答案总是有答案:
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
这很好,因为它向我展示了与答案相关的问题,但我也想要所有的问题,无论有没有答案。然后使用join而不是left join,非常感谢。第一个查询满足了我的需要。