私はこのようなテーブルを持っています:
CREATE TABLE IF NOT EXISTS `answered` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`correct` tinyint(1) NOT NULL DEFAULT '0',
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
と
CREATE TABLE IF NOT EXISTS `questions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
正解と不正解の数を選択する必要がありますが、同じ質問に複数の回答があった場合(同じquestion_idで「answered」にさらにエントリがある場合があります)、最新の(「answered.created」で決定)のみがカウントされます。
結果の構造は次のようになります。
correct count
0 1
1 3
フィドル: http ://sqlfiddle.com/#!2/11073
私の試用版:
SELECT a.correct, count(*) as count
FROM answered a
JOIN questions q ON a.question_id = q.id
GROUP BY correct
これは機能しますが、同じquestion_idsを複数回カウントします。