2

私は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
    )

クエリを修正できますか、それともおそらく左結合を持つ別のタイプのクエリが必要ですか?

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 に答える