我有以下方案:
CREATE TABLE IF NOT EXISTS `answers` (
`id` bigint(20) unsigned NOT NULL,
`answer` varchar(200) NOT NULL,
`username` varchar(15) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`,`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `answers` (`id`, `answer`, `username`, `date`) VALUES
(1, 'gfdsf', 'guy', '2012-12-22 00:00:00'),
(4, 'gfdddsfs', 'maricela', '2012-12-22 00:00:00'),
(4, 'gfddsfs', 'mikha', '2012-12-22 00:00:00'),
(4, 'gfdsfs', 'guy', '2012-12-22 00:00:00');
CREATE TABLE IF NOT EXISTS `questions` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`asker_username` varchar(15) NOT NULL,
`target_username` varchar(15) NOT NULL,
`question` varchar(200) NOT NULL,
`hide` enum('y','n') NOT NULL DEFAULT 'n',
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `questions` (`id`, `asker_username`, `target_username`, `question`, `date`) VALUES
(1, 'mikha', 'guy', 'testo festo', '2012-12-22 00:00:00'),
(2, 'mikha', 'guy', 'saaaaaaaar', '2012-12-22 00:00:00'),
(3, 'sys.tem', 'every.one', 'test g1', '2012-12-06 00:00:00'),
(4, 'sys.tem', 'every.one', 'test g2', '2012-12-06 00:00:00');
我使用以下查询:
SELECT
questions.id AS questionid,
COUNT(answers.username) AS count_everyone,
answers.username
FROM questions
LEFT JOIN answers ON questions.id = answers.id
GROUP BY questions.id,answers.username
问题出在COUNT(answers.username
. 我想计算每个问题的答案,但查询显示计数为 1。例如,问题 ID 4 被回答 3 次,但COUNT(answers.username)
显示为 1 而不是 3。
这是预期的结果:
questionid count_everyone username
1 1 guy
2 0 null
3 0 null
4 3 guy
4 3 maricela
4 3 mikha
这是我实际得到的结果:
questionid count_everyone username
1 1 guy
2 0 null
3 0 null
4 1 guy
4 1 maricela
4 1 mikha
谢谢