我想加入3张桌子。 学生,迟到和缺勤。
学生包含每位学生所需的信息。
迟到和旷工。他们的结构几乎相同。两者都包含相同的列,如student_id,date等...
我的目标是计算旷工和迟到的数量,并将其与具有相同student_id的学生放在同一行。
实施例。 学生表:
student_id date
a2 January 1,2016
a4 January 23,2016
迟到表:
student_id date
a1 Feb. 2,2009
a2 August 3,2011
a2 August 4,2011
a4 March 18,2016
a4 June 28,2016
a4 June 29,2016
a4 July 15,2016
a4 July 16,2016
a4 July 29,2016
旷工表:
SELECT students.student_id,
COUNT(absenteeism.student_id) AS absents,
COUNT(tardiness.student_id) AS tardi
FROM students
LEFT JOIN absenteeism ON students.student_id = absenteeism.student_id
LEFT JOIN tardiness ON students.student_id = tardiness.student_id
GROUP BY students.student_id
我已经尝试了一些。但这是我到目前为止最接近的一个。
student_id absents tardi
a1 1 0
a2 2 2
a3 0 0
a4 6 6
结果是
student_id absents tardi
a1 1 0
a2 2 1
a3 0 0
a4 6 1
我只有正确的数量。问题是a2和a4总是有相同数量的缺席和拖延。
正确的结果应该是这样的......
{{1}}
答案 0 :(得分:0)
我终于在这个主题MYSQL Left Join COUNTS from multiple tables
的帮助下弄明白了我在计数方面添加了明显的内容,并使用每个表格的主键而不是student_id。
SELECT students.student_id,
COUNT(distinct absenteeism.absent_id) AS absents,
COUNT(distinct tardiness.tardi_id) AS tardi
FROM students
LEFT JOIN absenteeism ON absenteeism.student_id = students.student_id
LEFT JOIN tardiness ON tardiness.student_id = students.student_id
GROUP BY students.student_id
我的错误是在旷工和拖延时使用相同的专栏 student_id 。这就是使用
的原因COUNT(distinct absenteeism.student_id)
COUNT(distinct tardiness.student_id)
只会导致
student_id absents tardi
a1 1 0
a2 1 1
a3 0 0
a4 1 1