Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count all instance in the join for each row?

I have the following scheme:

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');

I use the following query:

   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

The problem is with the COUNT(answers.username. I want to count the answers for each question but the query displays the count as 1. For example the question ID 4 is answered 3 times but the COUNT(answers.username) displays it as 1 instead of 3.

This is the expected result:

         questionid count_everyone  username
               1         1            guy
               2         0            null
               3         0            null
               4         3             guy
               4         3           maricela
               4         3             mikha

This is the result I actually get:

         questionid count_everyone  username
               1         1            guy
               2         0            null
               3         0            null
               4         1             guy
               4         1           maricela
               4         1             mikha

Thanks

like image 795
Michael Samuel Avatar asked Dec 22 '12 20:12

Michael Samuel


1 Answers

select q.id, coalesce(j.AnswerCount, 0) as AnswerCount, a.username

from questions q

left outer join

(select id as Qid, count(answer) as AnswerCount
from answers
group by id) j

on q.id = j.Qid

left outer join 
answers a on q.id = a.id
like image 138
ExactaBox Avatar answered Oct 02 '22 13:10

ExactaBox