对表执行插入操作时,会自动根据其父表检查外键以确保该值存在。如果它不存在,则插入失败。

我的问题是,仅仅为了插入时的数据检查而将值设置为外键是错误的吗?

我正在尝试做的一些 Nerd 的背景:

我正在建立一个摔跤数据库来复习我从大学开始就忘记的一切。作为一名摔跤迷,我认为将其用作主题会保持我的兴趣(并且确实如此)。

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)
)

对于“标题”表,我将 Current_Holder 和Former_Holder 字段设置为外键,以检查 Superstar_ID 在插入时实际存在的 Superstar 表。

这是非常错误的吗?仅将外键用于内置检查约束?

最佳答案

这就是约束的全部意义——检查数据是否一致。所以,不,它完全没问题。实际上,这是鼓励的 - 保持您的数据完整性,这样您就不会得到不存在的人“持有”的东西。

编辑 :我所说的“鼓励”的意思是,虽然您应该这样做,但技术使您不能这样做。如果您想手动检查,那么您可以不强制数据库中的外键关系。但是,您 在某处执行检查,否则,您最终会得到无用的数据。既然您正在学习 SQL 技能,那么我想最好利用您正在使用的 RDMBS 的所有功能。

关于sql - 使用外键只是为了防止数据插入? SQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14789033/

10-13 07:58
查看更多