mysql count 0_用mysql group by显示count为0的行

bd96500e110b49cbb3cd949968f18be7.png

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?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值