私のようなクエリがあります
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 |
+--------------+-------+
誰かがこのクエリを改善するのを手伝ってくれる?
ありがとう
labels
と呼びましょう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(一部が欠落している可能性があるもの)」です。