MYSQL 统计每个班有多少个学生

pkkgu1 2016-03-09 02:25:59
create temporary table classname
select 1 as cid, '小一班' as cid_name
union all select 2, '小二班'
union all select 3, '小三班'
union all select 4, '中一班'
union all select 5, '中二班'
union all select 6, '中三班'
union all select 7, '大一班'
union all select 8, '大二班';


create temporary table temp2
select 1 as sid, '张一' as sid_name, 2 as cid
union all select 2, '张二', 1
union all select 3, '张三', 1
union all select 4, '张四', 3
union all select 5, '张五', 2
union all select 6, '张六', 5
union all select 7, '张七', 6
union all select 8, '张八', 6;


MYSQL 统计每个班有多少个学生
...全文
2333 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
深蓝999 2020-02-26
  • 打赏
  • 举报
回复
Select Select Sid ,count (1) num from temp2 group by sid
weishaolin13x 2016-03-16
  • 打赏
  • 举报
回复
如果为0的也要统计,那用 : select a.cid_name ,count(b.cid) c from classname a left join temp2 b on a.cid=b.cid group by a.cid,a.cid_name
weishaolin13x 2016-03-16
  • 打赏
  • 举报
回复
最好不要用相关子查询,每条记录都执行一次子查询,效率相当慢
weishaolin13x 2016-03-16
  • 打赏
  • 举报
回复
select a.cid_name ,count(*) c from classname a inner join temp2 b on a.cid=b.cid group by a.cid,a.cid_name
ACMAIN_CHM 2016-03-09
  • 打赏
  • 举报
回复
select cid,cid_name, (select count(*) from temp2 where cid=classname.cid) from classname

56,682

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧