我的count(*)函数没有返回正确的值

时间:2018-03-26 13:09:01

标签: mysql sql

我应该写一个只显示专业的查询 以及每个专业的学生人数,即使是没有学生的专业也是如此

select S.first_name, m.major ,count(*) as 'Number of Majors '
from student S
inner join advisor_student SA on S._SID_ = SA.SID
right join major m on  SA.MID_ = m._MID_
group by major;

2 个答案:

答案 0 :(得分:0)

你需要使用左连接到学生表,你不应该取得学生姓名,除非你没有连接它。

select  m.major ,count(s.first_name)+ count(sa.first_name) as 'Number of Majors '
from major m
left join advisor_student SA on S._SID_ = SA.SID
left join student s on  S.MID_ = m._MID_
group by major;

答案 1 :(得分:0)

无需加入学生:

select m.major
   -- count(*) returns 1 for majors without student
   -- must count a column from the inner table which is NOT NULL
   -- usually done using the join column
   ,count(SA.MID_) as 'Number of Majors '
from major m
left join advisor_student SA 
  on  SA.MID_ = m._MID_
group by major;