Domanda

I have a relational database with an Address entity that should have a parent Address or a parent Unit, but not both. Currently the schema is Address having a ParentUnitID field and an ParentAddressID field. Is there a way to change this that prevents an Address from having both a parent Address and a parent Unit at the same time, but retains the foreign key constraints?

È stato utile?

Soluzione

A FOREIGN KEY is not enforced on a NULL value, so you just need to make sure that only one of them is non-NULL:

CHECK (
    (ParentUnitID IS NOT NULL AND ParentAddressID IS NULL)
    OR (ParentUnitID IS NULL AND ParentAddressID IS NOT NULL)
)

If you happen to use MySQL, you'll need to implement this as a trigger, since MySQL doesn't enforce CHECK constraints.

Alternatively, you could use inheritance, as described here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top