Let's say I have a relation: CourseRegistrations with composite primary key: (course_id, sem_id, student_id)
I have another relation: CourseEvaluations with composite primary key: (course_id, sem_id, section, type, serial)
.The CourseEvaluations relation will contain records of the different evaluations done in a course.
Now I want to make a third relation: CourseStudentEvaluations with two composite foreign keys from both the above tables. Both the above tables' primary keys contain course_id and sem_id. How do I enforce that they are equal in a row/record so that I can ensure only those students' evaluations are entered against only those courses in which they're registered.
The CourseStudentEvaluations relation will contain records of all students' performance in each evaluation entered in CourseEvaluations.
Best Answer
If your database supports it, you can use a table level CHECK constraint to compare two columns to make sure that they're equal. You could have a single CHECK constraint that confirms the
course_id
andsem_id
pointing to each parent are the same.Alternatively, you could just have one
course_id
and onesem_id
in your new table and use these columns in both of the foreign keys (one to each parent).I think the second approach is a little cleaner, but if you're using some kind of ORM that has trouble understanding a child table column pointing at two different parents then you may not find the second approach to be practical.