I have two tables:
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). 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.
if that's the case, why wouldn't you just allow null
value on the HomeAddressID
on the Customers
table? 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
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'. This way your foreign key constraint is valid.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.