MYSQL - 使用COUNT()连接多个表

时间:2017-04-02 07:01:14

标签: mysql

我被要求为学生的迟到和学校政策的违规行为创建一个数据库。

现在,我有三个单独的表:

tbl_ClassList:

  Student_ID    Student_Name 
  1000          Lee, Jonder
  1001          Chow, Stephen
  1002          Kim, Martin
  1003          Johns, Kevin
  1004          Hearfield, Olivia
  1005          Jarrs, Marlon

tbl_Tardy:

  Record_No Student_ID
          1 1001 
          2 1001
          3 1000
          4 1003
          5 1002
          6 1003
          7 1001
          8 1001
          9 1002
         10 1004

tbl_Violation:

  Record_No Student_ID
          1 1000
          2 1000
          3 1004
          4 1005
          5 1001
          6 1002
          7 1003

我被要求做的是生成一个列表,其中包含有关学生的信息,包括他/她的ID,姓名,迟到的数量和违规次数。像这样:

   Student_ID   Student_Name        No. of Tardy    No. of Violation
         1000   Lee, Jonder         1               2
         1001   Chow, Stephen       4               1
         1002   Kim, Martin         2               1
         1003   Johns, Kevin        2               1
         1004   Hearfield, Olivia   1               1
         1005   Jarrs, Marlon       0               1

我可以使用任何类型的连接来实现输出吗?请帮帮我。

1 个答案:

答案 0 :(得分:1)

您可以在子查询中找到针对迟到和违规的单独聚合,并使用classlist表找到它们left join。如果没有迟到/违规行,请使用coalesce获取零。

select c.*,
    coalesce(t.count_tardy, 0) as no_of_tardy,
    coalesce(v.count_violations, 0) as no_of_violations,
from tbl_classlist c
left join (
    select student_id,
        count(*) as count_tardy
    from tbl_tardy
    group by student_id
    ) t on c.student_id = t.student_id
left join (
    select student_id,
        count(*) as count_violations
    from tbl_violation
    group by student_id
    ) v on c.student_id = v.student_id;