【问题标题】:mysql count rows from another table with a where clausemysql使用where子句从另一个表中计算行数
【发布时间】:2019-03-06 18:44:53
【问题描述】:

大家好,需要一些帮助

如何使用 where 子句计算另一个表中的行数

所以我有两张桌子

表学生和出勤表我要统计所有对应学生的出勤表

这里是学生表

这里是为了出席餐桌

我试过这个,但只是获取有出勤率的学生

SELECT student.StudentID, student.`Name`, COUNT(attendance.AttendanceID) AS Total
FROM student
LEFT JOIN attendance ON student.StudentID = attendance.StudentID
where DateEntered between '2018-10-01' and '2018-10-01' 
GROUP BY student.StudentID,student.`Name`

我想要做的是获取所有学生并计算他/她出勤的次数。用 A where DateEntered

谢谢你的帮助.......

【问题讨论】:

标签: mysql


【解决方案1】:

将条件放在左连接子句中:

SELECT student.StudentID, student.`Name`, COUNT(attendance.AttendanceID) AS Total
FROM student
LEFT JOIN attendance ON student.StudentID = attendance.StudentID
    and DateEntered between '2018-10-01' and '2018-10-01' 
GROUP BY student.StudentID,student.`Name`

【讨论】:

    【解决方案2】:

    您可以在关于出席的聚合查询中离开 join student

    SELECT     s.StudentID, 
               s.Name,
               COALESCE(Total, 0) 
    FROM       student s
    LEFT JOIN  (SELECT StudentId, COUNT(*) AS total
                FROM   attendance
                GROUP BY StudentId) ON s.StudentId = a.StudentId
    WHERE      DateEntered BETWEEN '2018-10-01' and '2018-10-01'
    

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 2018-10-28
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多