I have a table of Students and a table of Courses that are connected through an intermediate table to create a many-to-many relationship (ie. a student can enroll in multiple courses and a course can have multiple students). The problem is that the client wants a unique student ID per course. For example:
rowid Course Student ID (calculated)
1 A Ben 1
2 A Alex 2
3 A Luis 3
4 B Alex 1
5 B Gail 2
6 B Steve 3
The ID's should be numbered from 1 and a student can have a different ID for different course (Alex for example has ID=2 for course A, but ID=1 for Course B). Once an ID is assigned it is fixed and cannot change. I implemented a solution by ordering on the rowid of the through table "SELECT Student from table WHERE Course=A ORDER BY rowid" and then returning a number based on the order of the results.
The problem with this solution, is that if a student leaves a course (is deleted from the table), the numbers of the other students will change. Can someone recommend a better way? If it matters, I'm using PostgreSQL and Django. Here's what I've thought of:
- Creating a column for the ID instead of calculating it. When a new relationship is created assigning an ID based on the max(id)+1 of the students in the course
- Adding a column "disabled" and setting it True when a student leaves the course. This would involve changing all my code to make sure that only active students are used
I think the first solution is better, but is there a more "database centric way" where the database can calculate this for me automatically?