tags:

views:

2061

answers:

2

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?

A: 

Try

Select company.cname, count(work.id) from company left join work on ....=.... group by company.cname

where you fill out the "...." parts, and change the work.id to you name

Erik
+2  A: 

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
Tomalak
P.S.: You should dump NATURAL JOINs. They seem to be handy, but they are not really useful, IMHO. They water down your expressive capabilities and they make implications on how to design your database (column naming), which is a big WTF for me.
Tomalak