简体   繁体   中英

How can I make this database schema better?

I currently have two tables in which stores the attendances of a student in a course. I have the hub_attendance table which stores the total attendances of a student and the hub_attendance_lesson where it stores the attendance of each lesson that a student has or has not attended. I'm not sure if this is correct or if I'm doing anything wrong, I'm a beginner in databases!

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

EDIT:

So I've gotten rid of the first table completely and this is my new single table.

Hub_Attendance:
id
lesson_id
course_id
student_id
date
attendance

As Dutchie432 said, you don't need the first table because it introduces unnecessary redundancy and you can count those statistics on the fly. Such aggregate tables can be a good solution if performance is an issue, but they should be used only as a last resort.

About the second table - you have separate fields attended , absent , excused_absent , late and excused_late . Aren't these mutually exclusive? So only one of them can be true for one row? If so, you may be better off with one enumeration field called for example attendance , which would take different values for each of those states. In that way you could't have rows where none of the flags, or more than one flag, is set.

Here's what you need:

**Course**
id, name, etc...

**Lesson**
id, courseid, name, etc...

**Attendance**
id, studentid, lessonid, lateness, etc...

**Enrolment**
id, courseid, studentid, startdate, etc...

You need the enrolment table to know that students should be on a course even if they never turn up for lessons. The attendance table will allow you to have many students per lesson and many lessons per student. This is a many-to-many table . Any aggregation and counting can be done in SQL.

If I understand your schema correctly, Your first table can be totally eliminated. You should be able to fetch the totals using MySQL.

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

Remove this first table, every total can be fetch using SQL :

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

I guess you'll be able to adapt this code for your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM