student
name class
张三 1
李四 1
王五 2
赵六 2
孙七 3
然后查询出来的结果得是
class count
1 2
2 2
3 1
4 0
--------------------
可以在加一个班级表
id class
1 1
2 2
3 3
4 4
select c.class, count(s.name) as count from class c left join student s on c.class = s.class group by c.class
select c.id,count(s.name)
from
(select 1 as id from dual
union all select 2 as id from dual
union all select 3 as id from dual
union all select 4 as id from dual) c left join student s on s.class=c.id
group by c.id
ps:个人感觉这样有点无厘头,建议班级有一个具体的表来维护,真实业务中班级不应该只有一个1,2,3,4这类字段吧,有一些属性也可以都加进去
你先将各班的人数统计出来,然后你有班级表对吧?你用班级表作为主表,左连接你统计完人数的那张表,班级对应的人数是空值的你就给0,这样不就所有班级都有了嘛,没统计到的自然也是0了。
select * from student e left join (select class,count(*) 人数 from student group by class) s on s.class=e.class;
不知道你说的是不是这个意思,加了一个虚拟的表,在这一个里面完成查询。每个学生后面都有所在班级 的人数
select t2.class,(select count(1) from student t1 where t1.class = t2.class)
from class t2