web-dev-qa-db-ja.com

カウントがゼロの左結合と内部結合による結果のグループ化

私のようなクエリがあります

SELECT 
    `campaign_question_options`.`text`, 
    COUNT(`campaign_submission_answers`.`answer`) as `count`
    FROM `campaign_questions`
    INNER JOIN `campaign_question_options` ON `campaign_question_options`.`campaign_question_id` = `campaign_questions`.`id`
    LEFT JOIN `campaign_submission_answers` ON `campaign_submission_answers`.`answer` = `campaign_question_options`.`text` AND `campaign_submission_answers`.`campaign_question_id` = 1
    LEFT JOIN `campaign_submissions` ON `campaign_submissions`.`id` = `campaign_submission_answers`.`campaign_submission_id`
    LEFT JOIN `participants` ON `participants`.`id` = `campaign_submissions`.`participant_id`
WHERE 
    `campaign_questions`.`id` = 1
GROUP BY `campaign_submission_answers`.`answer` 
ORDER BY `campaign_question_options`.`index`;

これは私に次のような結果セットを与えます

+--------------+-------+
|     text     | count |
+--------------+-------+
| 1 (positive) |   114 |
| 2            |    48 |
| 3 (neutral)  |    34 |
| 4            |     6 |
| 5 (negative) |     0 |
+--------------+-------+

したがって、問題は、結果をparticipants.appraisee_id列でさらにフィルター処理する必要があることです。ただし、これをwhere句に追加すると、ゼロの結果が失われます(左結合がnull行を返すため)。

SELECT 
    `campaign_question_options`.`text`, 
    COUNT(`campaign_submission_answers`.`answer`) as `count`
FROM `campaign_questions`
INNER JOIN `campaign_question_options` ON `campaign_question_options`.`campaign_question_id` = `campaign_questions`.`id`
LEFT JOIN `campaign_submission_answers` ON `campaign_submission_answers`.`answer` = `campaign_question_options`.`text` AND `campaign_submission_answers`.`campaign_question_id` = 1
LEFT JOIN `campaign_submissions` ON `campaign_submissions`.`id` = `campaign_submission_answers`.`campaign_submission_id`
LEFT JOIN `participants` ON `participants`.`id` = `campaign_submissions`.`participant_id`
WHERE 
    `campaign_questions`.`id` = 1 AND `participants`.`appraisee_id` = 1
GROUP BY `campaign_submission_answers`.`answer` 
ORDER BY `campaign_question_options`.`index`;

どっちが帰る

+--------------+-------+
|     text     | count |
+--------------+-------+
| 1 (positive) |    16 |
| 2            |     1 |
+--------------+-------+

実際に私が望むとき

+--------------+-------+
|     text     | count |
+--------------+-------+
| 1 (positive) |    16 |
| 2            |     1 |
| 3 (neutral)  |     0 |
| 4            |     0 |
| 5 (negative) |     0 |
+--------------+-------+

誰かがこのクエリを改善するのを手伝ってくれる?

ありがとう

2
Bowen
  1. N = 1..5とコメント(ポジティブなど)でテーブルを作成します。 labelsと呼びましょう
  2. カウントを取得する(5以下)
  3. まとめる:

SELECT labels.n, labels.comment, IFNULL(x.ct, 0) AS "count" FROM labels LEFT JOIN ( your big query to get the counts ) x ON x.n = labels.n ORDER BY labels.n

原則は、「FROM(必要なものすべて)[〜#〜] left [〜#〜] JOIN(一部が欠落している可能性があるもの)」です。

3
Rick James