Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying rows with count 0 with mysql group by

Tags:

mysql

group-by

I have two tables in MySql Company : (cname,city) works : (ename,cname,salary)

I want to display number of employees working for every company, even if that number is zero.

for e.g. for

Company : 
Microsoft Bangalore
IBM       NY

works : 
emp1 Microsoft 10000
emp2 Microsoft 90000

output should be :

Microsoft 2
IBM 0

But the following query and other similar queries print only those companies which have at least one employee :

Select count(*) from works natural join company group by company.cname

If I use outer join, then the companies with zero employees will still show up in one row, so that option is out as well.

How to do it?

like image 913
simplfuzz Avatar asked Apr 13 '09 09:04

simplfuzz


1 Answers

Classic case for a LEFT JOIN:

SELECT
  c.cname,
  COUNT(w.ename) wcount 
FROM
  company c
  LEFT JOIN works w ON c.cname = w.cname
GROUP BY
  c.cname
like image 155
Tomalak Avatar answered Sep 29 '22 00:09

Tomalak