2

I have 2 tables, a questions and an answers table as so:

question : id, title, description, date, company_id
answers  : id, question_id, answer, date, company_id

I want a list of all questions asked whether they have answers or not and also all answers provided. I have done this without any trouble but the part of I am unsure on is how to provide the question title in the answer array as I want to display which question an answer relates to.

Currently I have this query:

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

This almost provides me with what I want:

[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
    )

The only difference is that I want to cross reference the question table and add the question title to the answer so that it looks like this:

[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
    )

Can I amend my query or do I need another type of query with a left join perhaps?

4

2 回答 2

1

你需要的是一个加入

Select * from answers left join question on answers.question_id = question.id;
于 2013-11-03T14:18:44.090 回答
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
于 2013-11-03T14:28:46.487 回答