【问题标题】:mysql select of selectmysql 选择的选择
【发布时间】:2021-09-14 12:09:33
【问题描述】:

表学生

StudentID StudentName
1 A
2 B
3 C

桌书

BookID BookName
1 Book1
2 Book2
3 Book3

桌书作业

AssignID BookID StudentID DateTime
1 1 1 2021-06-26
2 2 1 2021-07-01
3 1 2 2021-07-03

结果表应该是

StudentID StudentName BookCount
1 A 2
2 B 1
3 C 0

如何在一次 SQL 执行中获取结果表? Left JOIN 似乎不是一种选择,因为它消除了 StudentID 3

刚刚在 BookAssignment 表中添加了另一个 DateTime 列 - 查询过去连续 7 天的图书数量的 SQL 语法是什么(即使是 0 本书的天数)?

【问题讨论】:

    标签: mysql sql select count


    【解决方案1】:

    您需要通过在两个表之间使用左连接来使用简单组:

    select s.StudentID, s.StudentName , count(*) BookCount 
    from students s
    left join books b
      on s.StudentID = b.StudentID
    group by s.StudentID, s.StudentName
    

    【讨论】:

      【解决方案2】:

      我会在书籍的聚合查询中加入 student 表,并使用 coalesce 填充零:

      SELECT    s.StudentID, StudentName, COALESCE(cnt, 0)
      FROM      student s
      LEFT JOIN (SELECT   StudentID, COUNT(*) AS cnt
                 FROM     books
                 GROUP BY StudentID) b ON s.StudentID = b.StudentID
      

      【讨论】:

      • 在 COUNT(*) 之后缺少 cnt - 效果很好。谢谢
      • @KennethN 确实,我的错。感谢您的关注。已编辑和修复。
      【解决方案3】:

      您也可以使用相关子查询:

      select s.*,
             (select count(*)
              from books b
              where s.StudentID = b.StudentID
             ) as bookCount
      from students s;
      

      这比使用join/group by 方法有一些优势:

      • 您可以轻松地将所有列包含在select 中。他们不必在group by 中重复。
      • 使用books(StudentID) 上的索引,这通常具有最佳性能。
      • 这样可以避免可能会影响性能的外部聚合。
      • 添加另一个维度(比如学生的课程数量)很有效,无需担心笛卡尔积。

      【讨论】:

      • 非常干净和强大。谢谢
      【解决方案4】:

      select s.StudentID, s.StudentName ,(select count(*) from BookAssignment b where b.studentid = s.studentid) as BookCount 来自学生的

      【讨论】:

        猜你喜欢
        • 2012-09-12
        • 1970-01-01
        • 2021-11-19
        • 2013-04-20
        • 2011-02-27
        • 1970-01-01
        • 2017-11-01
        • 2011-06-02
        • 1970-01-01
        相关资源
        最近更新 更多