对表执行插入操作时,会根据其父表自动检查外键以确保该值存在。如果它不存在,则插入失败。
我的问题是,将值设置为外键仅仅是为了插入数据检查是错误的吗?
我正在尝试做的一些讨厌的背景:
我正在建立一个摔跤数据库来清理自大学以来我忘记的一切。作为一个摔跤迷,我认为将它作为一个主题会让我感兴趣(而且它有)。
Create Table Superstar
(
Superstar_ID Int Not Null Primary Key Identity (100,1),
Employee_ID Int Not Null Foreign Key References Employee(Employee_ID),
Alignment_ID Int Not Null Foreign Key References Alignment(Alignment_ID),
SuperStar_Name Varchar(50) Not Null,
SuperStar_Weight Varchar(50) Not Null,
SuperStar_Height Varchar(50) Not Null,
Billed_From Varchar(50) Not Null,
Active Bit Not Null
)
Create Table Title
(
Title_ID Int Not Null Primary Key Identity(1,1),
Title_Name Varchar(50) Not Null,
Title_Description Varchar(50) Not Null,
**Current_Holder Int Foreign Key References Superstar(Superstar_ID),
Former_Holder Int Foreign Key References Superstar(Superstar_ID),**
Active Bit Not Null
)
Create Table Superstar_Title
(
Superstar_Title_ID Int Not Null Primary Key Identity (1,1),
Title_ID Int Not Null Foreign Key References Title(Title_ID),
Superstar_ID Int Not Null Foreign Key References Superstar(Superstar_ID)
)
对于'Title'表,我将Current_Holder和Former_Holder字段设置为外键,以检查Superstar表,其中Superstar_ID实际上存在于插入中。
这非常错吗?仅使用外键来构建内置检查约束?
答案 0 :(得分:3)
这是一个约束的全部要点 - 检查数据是否一致。所以,不,这完全没问题。实际上,它是鼓励的 - 保持您的数据完整性,这样您就不会得到被不存在的人“抓住”的东西。
编辑:我所说的“鼓励”是指,虽然你应该这样做,但技术却让你无法做到。如果要手动检查,则可以自由地不在数据库中强制执行外键关系。但是,您有在某处执行检查,否则,您将最终得到无用的数据。既然你正在研究你的SQL技能,那么我想最好利用你正在使用的RDMBS的所有功能。