[英]Can I use same Foreign key for different tables in sql
假设我正在为教师创建投票系统,并希望将voting_id作为两张桌子的老师和高级教师的主键,并且将voting_id成为新桌子中两个桌子的单个外键,那么我可以选民吗?
Why do you want to have separate tables for teachers and senior teachers? 您为什么要为教师和高级教师分别设置表格? It seems highly likely that those are really the same entity that should be modeled with a single
teacher
table that has a senior_teacher
attribute. 这些实体实际上很有可能是同一实体,应该使用具有
senior_teacher
属性的单个teacher
表进行建模。 You would then create a voter
table with a teacher_id
column that refers to the teacher_id
primary key in the teacher
table. 然后,您将创建一个带有
teacher_id
列的voter
表,该列引用了teacher
表中的teacher_id
主键。 It doesn't make sense for the primary key of the teacher
table to be voter_id
rather than teacher_id
. 它没有意义的主键的
teacher
表是voter_id
而非teacher_id
。
I would model it differently. 我会以不同的方式建模。 Teacher can have N votes(1:N relation).
老师可以有N票(1:N关系)。 So the votes table has teacher_id, probably a grade and timestamp.
因此,票表中有Teacher_id,可能是年级和时间戳。 I would put teacher and senior teacher in the same table and add a type column to it(senior or normal), because senior teacher is just an extended type of a teacher.
我将老师和高级老师放在同一个表中,并在其中添加一个类型列(高级或普通),因为高级老师只是老师的扩展类型。
Voting_id can't be primary key because it identifies vote not the teacher. Voting_id不能作为主键,因为它标识的是投票,而不是老师。 Also you would have collisions because teacher and senior teacher can have the same primary id if they are in two seperate tables.
同样,您也会发生冲突,因为如果教师和高级教师在两个单独的表中,他们可以具有相同的主要ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.