+ -
当前位置:首页 → 问答吧 → 【【【【请教大神,mysql读取count(id)后为0的不显示?求解】】】】

【【【【请教大神,mysql读取count(id)后为0的不显示?求解】】】】

时间:2011-08-04

来源:互联网

表:team - 字段: id、title、city_id
表:category - 字段: id、name

数据:
team:
id | title | city_id |
1 | 测试 | 1
2 | 测试 | 2
3 | 测试 | 3
4 | 测试 | 1
5 | 测试 | 1
6 | 测试 | 2

category:

id | name |
1 | 湖南
2 | 深圳
3 | 广州
4 | 杭州
5 | 东北
6 | 北京


最后想显示的结果是这样的:
name | count(team.id) |
  湖南 | 3
  深圳 | 2
  广州 | 1
  杭州 | 0
  东北 | 0
  北京 | 0



总之就是count为0的数据,也要显示出来..
求大神指点....

作者: jauia   发布时间: 2011-08-04

用right join


select B.name,count(*)
from team A right join category b on A.cityid=B.id
group by B.name

作者: rucypli   发布时间: 2011-08-04

select name,count(team.id)
  from category left join team on category.id=team.id
  group by name

作者: ACMAIN_CHM   发布时间: 2011-08-04

SQL code


create table team(id int,title varchar(10),city_id int,);
insert into team
select 1,'测试',1 union all
select 2,'测试',2 union all
select 3,'测试',3 union all
select 4,'测试',1 union all
select 5,'测试',1 union all
select 6,'测试',2  ;

create table category(id int,name varchar(10));
insert into category
select 1,'湖南' union all
select 2,'深圳' union all
select 3,'广州' union all
select 4,'杭州' union all
select 5,'东北' union all
select 6,'北京'  ;

select name,count(a.city_id) 
from team a right join category b on a.city_id=b.id
group by b.name 
order by count(a.city_id) desc


--------------
--湖南    3
--深圳    2
--广州    1
--杭州    0
--北京    0
--东北    0


作者: JQ_ii_QC   发布时间: 2011-08-04