Py学习  »  DATABASE

mysql选择

Kenneth N • 3 年前 • 1279 次点击  

桌上学生

学生 学生名
1. A.
2. B
3. C

餐桌簿

书呆子 书名
1. 第一册
2. 第二册
3. 第三册

表格图书分配

转让人 书呆子 学生 约会时间
1. 1. 1. 2021-06-26
2. 2. 1. 2021-07-01
3. 1. 2. 2021-07-03

结果表应该是

学生 学生名 书数
1. A. 2.
2. B 1.
3. C 0

如何在一次SQL执行中获得结果表? 左连接似乎不是一个选项,因为它消除了StudentID 3

刚刚在BookAssignment表中添加了另一个DateTime列——在过去的7个连续的天中(即使对于0 book for day count),查询图书计数的SQL语法是什么?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129771
 
1279 次点击  
文章 [ 4 ]  |  最新文章 3 年前
assaduzzaman samrat
Reply   •   1 楼
assaduzzaman samrat    3 年前

选择s.StudentID,s.StudentName,(从BookAssignment b中选择count(*),其中b.StudentID=s.StudentID)作为BookCount 来自学生的

Gordon Linoff
Reply   •   2 楼
Gordon Linoff    3 年前

还可以使用相关子查询:

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

这比使用 join / group by 方法:

  • 您可以轻松地将所有列包含在 select .他们不必在课堂上重复 分组 .
  • 带索引的 books(StudentID) 这通常有最好的表现。
  • 这避免了外部聚合,因为外部聚合可能会降低性能。
  • 添加另一个维度(比如学生的课程数量)只会起作用,而不用担心笛卡尔积。
Mureinik
Reply   •   3 楼
Mureinik    3 年前

我留下来加入学生表,对书籍和使用进行汇总查询 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
eshirvana
Reply   •   4 楼
eshirvana    3 年前

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

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