简体   繁体   English

SQL外键约束还是静态值?

[英]SQL Foreign Key Constraint or a static value?

I have two tables: 我有两个表:

  • Customer (Id, Name, HomeAddressId) 客户(ID,名称,HomeAddressId)
  • Address (Id, Street, City, State) 地址(身份证,街道,城市,州)

I want to place a foreign key constraint on Customer so that the HomeAddressId is valid, but I also want to allow -1 as a valid value (even if it isn't one of the Address.Id values). 我想在Customer上放置一个外键约束,以便HomeAddressId有效,但是我也想允许-1作为有效值(即使它不是Address.Id值之一)。 Is this actually possible? 这实际上可行吗? And, if so... how? 而且,如果是的话……怎么办?

No. Foreign keys are absolute and the value in the foreign key must be present in the primary key to which it refers. 否。外键是绝对的,外键中的值必须存在于它所引用的主键中。

You can, however, declare the foreign key column(s) as NULLable, and then use NULL for the "not known" or "not defined" value. 但是,您可以将外键列声明为NULLable,然后将NULL用作“未知”或“未定义”值。

if that's the case, why wouldn't you just allow null value on the HomeAddressID on the Customers table? 如果是这种情况,为什么不只在Customers表的HomeAddressID上允许null值? But still add foreign key constraint on it. 但是仍然在其上添加键约束。

CREATE TABLE Customer
(
    Id INT, 
    Name VARCHAR(50), 
    HomeAddressId INT NULL,
    CONSTRAINT tb_fk FOREIGN KEY (HomeAddressId) REFERENCES Address(ID)
)

You can't do this and you shouldn't. 您不能这样做,也不应这样做。 Since this is the main rule of the foreign key constraints, to ensure data consistency. 由于这是外键约束的主要规则,因此要确保数据的一致性。

May be you need to add a new column, something like IsValid as a flag for the validaity of the column value instead 可能是您需要添加一个新列,例如IsValid作为该列值有效性的标志

The solution in te above answers is the right way to do it. 以上答案中的解决方案是正确的方法。 However, if you still nee to stick to the -1 approach, create a default entry in the Address table with the ID as -1 and all the other columns as null or 'unknown'. 但是,如果您仍要坚持使用-1方法,请在“地址”表中创建一个默认条目,其ID为-1,所有其他列为null或“未知”。 This way your foreign key constraint is valid. 这样,您的外键约束才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM