mysql连接并统计记录数

r6hnlfcb  于 2021-07-27  发布在  Java
关注(0)|答案(2)|浏览(300)

我有两张table
tbl\U组:

id |   name        
----------------
 1 | BSCS
 2 | BSIT
 3 | BBA

tbl\U学生:

id |     name     | group_id
-------------------------------
 1 | Student Name |     1 
 2 | Student 2    |     1
 3 | Student 3    |     2

我想显示组的详细信息:组名和特定组中的学生人数,
我正在使用这个查询,但它显示有学生的组。它不显示有0个学生的组。

select tb2.id, tb2.name, count(*) from tbl_students tb1 JOIN tbl_groups tb2 ON tb1.group_id = tb2.id

我如何显示所有组,请给我一些想法
编辑:如果使用上述查询,则得到以下结果:

id |     name     | count(*)
-------------------------------
 1 | Student Name |     2
 2 | BSIT         |     1

(它不显示第三组,因为有0个学生,我也想显示这个组)。

cdmah0mi

cdmah0mi1#

只需使用左连接:

select tb2.id, tb2.name, count(tb1.id) as no_std 
  from tbl_groups tb2
        LEFT JOIN tbl_students tb1 ON tb2.id = tb1.group_id
group by tb2.id, tb2.name

现场观看:http://sqlfiddle.com/#!9/2282年3月5日

kqqjbcuj

kqqjbcuj2#

我只需要使用一个相关的子查询来获得每组学生的数量,如下所示:

select 
    g.*,
    (select count(*) from tbl_students s where s.group_id = g.id) no_students
from tbl_groups g

这不会过滤出没有学生的组(它将给出 0 相反)。还有一个索引 tbl_students(group_id) ,这应该是最有效的(如果您在该列上设置了外键约束,那么该索引已经存在了,这是您应该有的)。

相关问题