2013-11-03 84 views
2

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

我可以修改我的查询或我是否需要另一种带左连接的查询?

回答

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 
+0

非常好,非常感谢。第一个查询做了我所需要的。 – 2scope

1

你需要的是一个连接

Select * from answers left join question on answers.question_id = question.id; 
+0

这很棒,它向我展示了与答案相关的问题,但我也想要所有问题,无论有没有答案。 – 2scope

+0

然后用连接代替左连接 –