In SQL the foreign keys references primary keys only. Why cannot it refer to a unique not null indexed column that is clustered?
在SQL中,外键只引用主键。为什么它不能引用聚集的唯一非空索引列?
1 个解决方案
#1
6
This is not true of all RDBMS's. SQL Server (2008/R2) allows Foreign Keys on non-null columns which are either Unique Key Constraints or UNIQUE indexes (ie. the candidate key doesn't even need to be the Clustered Index). For example:
并非所有RDBMS都是如此。SQL Server (2008/R2)允许非空列上的外键,这些列要么是唯一的键约束,要么是唯一的索引。候选键甚至不需要是聚集索引)。例如:
CREATE TABLE Parent
(
ParentUnique1 INT NOT NULL,
ParentUnique2 INT NOT NULL,
Name NVARCHAR(50) NOT NULL
);
-- Some arbitrary PK
ALTER TABLE Parent ADD CONSTRAINT PK_Parent PRIMARY KEY(Name);
-- Unique Key Constraint
ALTER TABLE Parent ADD CONSTRAINT U_Parent UNIQUE(ParentUnique1);
-- Unique Index (NonClustered)
CREATE UNIQUE INDEX IX_Parent ON Parent(ParentUnique2);
CREATE TABLE Child1
(
ChildID INT NOT NULL,
ParentID INT NOT NULL,
CONSTRAINT FK_Child1Parent FOREIGN KEY(ParentID) REFERENCES Parent(ParentUnique1)
);
CREATE TABLE Child2
(
ChildID INT NOT NULL,
ParentID INT NOT NULL,
CONSTRAINT FK_Child2Parent FOREIGN KEY(ParentID) REFERENCES Parent(ParentUnique2)
);
#1
6
This is not true of all RDBMS's. SQL Server (2008/R2) allows Foreign Keys on non-null columns which are either Unique Key Constraints or UNIQUE indexes (ie. the candidate key doesn't even need to be the Clustered Index). For example:
并非所有RDBMS都是如此。SQL Server (2008/R2)允许非空列上的外键,这些列要么是唯一的键约束,要么是唯一的索引。候选键甚至不需要是聚集索引)。例如:
CREATE TABLE Parent
(
ParentUnique1 INT NOT NULL,
ParentUnique2 INT NOT NULL,
Name NVARCHAR(50) NOT NULL
);
-- Some arbitrary PK
ALTER TABLE Parent ADD CONSTRAINT PK_Parent PRIMARY KEY(Name);
-- Unique Key Constraint
ALTER TABLE Parent ADD CONSTRAINT U_Parent UNIQUE(ParentUnique1);
-- Unique Index (NonClustered)
CREATE UNIQUE INDEX IX_Parent ON Parent(ParentUnique2);
CREATE TABLE Child1
(
ChildID INT NOT NULL,
ParentID INT NOT NULL,
CONSTRAINT FK_Child1Parent FOREIGN KEY(ParentID) REFERENCES Parent(ParentUnique1)
);
CREATE TABLE Child2
(
ChildID INT NOT NULL,
ParentID INT NOT NULL,
CONSTRAINT FK_Child2Parent FOREIGN KEY(ParentID) REFERENCES Parent(ParentUnique2)
);