我有以下方案:如何統計每行的連接中的所有實例?
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
感謝
既然你通過用戶名進行分組,你爲什麼會想到每行一個以上的用戶名? – Barmar
如果我通過用戶名去除分組,只會顯示一個答案。我想同時顯示所有答案和他們的計數...謝謝:) –
maricela只回答了問題4一次,那麼爲什麼你期望計數是3? – Barmar