I’d like to ask regarding a particular issue I have.
For example, I have a Student table that has a SchoolID and a ClassID, both of which are foreign keys to the School and Classroom tables respectively. The Class table has a SchoolID column which is a foreign key to the School table.
Is there any way I can ensure that the ClassID in the Student table is a child of the SchoolID, or must I remove the SchoolID and just live with the ClassID in order to prevent any possible discrepancies?
Yes, technically you should remove the
Student.SchoolIdforeign key, if Class already hasSchoolId, as this already defines the relationship betweenStudentandSchool.That said, there are some common ‘exceptions’ to this, e.g.:
If the relationship between
StudentandSchoolcan mean something different than the relationship betweenClassandSchool(e.g. if the student goes to School X as ‘his/her main school’, but then also attends an extra mural Class Y at School Z). (Actually, this could highlight a modelling error, i.e. Student : Class might actually be a many to many relationship)For performance reasons it is sometimes (a somewhat reluctant) choice to add the parent’s foreign key to a child to avoid the need to join back to parent. But as you say, this can result in integrity issues.