如何使此数据库架构更好


How can I make this database schema better?

我目前有两个表,其中存储课程中学生的出勤情况。我有一个hub_attendance表,它存储了一个学生的总出勤率,hub_attendance_lesson它存储了一个学生已经或没有参加的每节课的出勤率。我不确定这是否正确,或者我是否做错了什么,我是数据库的初学者!

hub_attendance:
id
student_id
course_id
total_lessons
total_lessons_so_far
total_attended
total_absent
total_excused_absent
total_late
total_excused_late
hub_attendance_lesson:
id
lesson_id
course_id
student_id
date
attended
absent
excused_absent
late
excused_late

编辑:

所以我完全摆脱了第一个表,这是我的新单表。

Hub_Attendance:
id
lesson_id
course_id
student_id
date
attendance

正如 Dutchie432 所说,您不需要第一个表,因为它引入了不必要的冗余,您可以即时计算这些统计信息。如果性能存在问题,此类聚合表可能是一个很好的解决方案,但它们应仅作为最后的手段使用。

关于第二个表 - 您有单独的字段attendedabsentexcused_absentlateexcused_late .这些不是相互排斥的吗?所以一行只能有一个是真的?如果是这样,最好使用一个枚举字段,例如 attendance ,它将为每个状态采用不同的值。这样,您就不会有未设置任何标志或多个标志的行。

以下是您需要的:

**Course**
id, name, etc...
**Lesson**
id, courseid, name, etc...
**Attendance**
id, studentid, lessonid, lateness, etc...
**Enrolment**
id, courseid, studentid, startdate, etc...

您需要注册表才能知道学生应该参加课程,即使他们从未上课。出勤表将允许您每节课有很多学生,每个学生有很多课。这是一个多对多表。任何聚合和计数都可以在 SQL 中完成。

如果我正确理解您的架构,您的第一个表可以完全消除。您应该能够使用 MySQL 获取总计。

select count(id) as total_late from hub_attendance_lesson where late=true and student_id=TheUserId 

删除第一个表,可以使用 SQL 获取每个总数:

SELECT count(id) AS absent
FROM hub_attendance_lesson 
WHERE lesson_id = <your lesson id>
AND absent = <false / true>

我想您将能够根据需要调整此代码。