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

标签 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

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

最佳答案

您可以在子查询中找到单独的迟到和违规聚合,并将它们left join 到 classlist 表中。如果没有迟到/违规行,请使用 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;

关于MYSQL - 使用 COUNT() 连接多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43165522/

相关文章:

php - 在一个 id 中存储多个值

php - 在另一个查询结果对象中写入插入查询时插入双倍或更多值

php - 如何使用 PHP 从 mysql 中读取值

java - 如何使用Spring Boot查询并持久化MySQL数据库中的静态对象?

python - 哪种策略最好 : saving a value as a field or just computing it on hand with a method

python - Library not loaded : @rpath/libmysqlclient. 21.dylib Reason: image not found Django migrate error using mysqlclient DB 驱动程序和 MySQL 8 with macOS

Mysqli查询内连接错误

php - 多对多关系中选择的解决方案

mysql_query() 的 PHP 登录代码错误

php - 我可以阻止我的虚拟主机提供商访问我的 "mySQL"数据库中的信息吗?