问题
I'm looking for a constraint in an SQL table that will only allow one of two nullable columns to be set per row. Both columns are foreign keys that relate to different tables.
As an example, say each table row describes a section of a journey. I have a separate table for Cars and Planes.
Without redesigning my whole database to use a Vehicles table, how can I ensure that each journey row is done by either a CarID or a PlaneID, but never both at the same time, and never neither?
回答1:
Add a constraint something like this...
ALTER TABLE TableName
ADD CONSTRAINT ck_Nullable CHECK (
(CarID IS NULL AND PlaneID IS NOT NULL)
OR
(CarID IS NOT NULL AND PlaneID IS NULL)
)
来源:https://stackoverflow.com/questions/25138805/only-allow-one-of-two-columns-to-be-set