2017-04-02 125 views
1

我被要求为学生的迟到和学校政策违规创建数据库。现在MYSQL - 与COUNT连接多个表()

,我有三个独立的表:

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 

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

+0

你可以有一个简单的学生证 – Rams

回答

1

你可以在子查询中找到单独的聚合数据,并且可以在子查询中找到它们,left join可以使用classlist表查找它们。如果没有迟缓/违规行,使用​​3210以获得零。

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; 
+1

哇它的工作原理和加入群。非常感谢。 :) –