对特定子类型的外键引用

Foreign key reference to a specific subtype

这个问题来自 Foreign Key to multiple tables 但我认为我的阐述可以使用它自己的主题。

假设我有以下架构(改编自上面 link 中的 @Nathan Skerl's 答案):

    create table dbo.PartyType
(   
    PartyTypeId tinyint primary key,
    PartyTypeName varchar(10)
)

insert into dbo.PartyType
    values(1, 'User'), (2, 'Group');


create table dbo.Party
(
    PartyId int identity(1,1) primary key,
    PartyTypeid tinyint references dbo.PartyType(PartyTypeId),
    unique (PartyId, PartyTypeId)
)

CREATE TABLE dbo.[Group]
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(2 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyId, PartyTypeID)
)  

CREATE TABLE dbo.[User]
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(1 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID)
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    [Owner] int NOT NULL references dbo.Party(PartyId),
    [Subject] varchar(50) NULL
)

然后说我有另一个关系,比如 'Stuff',其中 'Users' 可以拥有 'Stuff' 的许多项,但是 'Groups' 没有意义'Stuff'。我可以在 'Stuff' 引用 'User' 中有一个外键吗?

如果可以的话,那要怎么做呢?还是我必须直接通过 'Party' 完成所有此类外键? 我得到一个错误(引用的 table 'dbo.Users' 中没有与外键 中的引用列 'ID' 匹配的主键或候选键)当我自己尝试时。

提前致谢!

如果我没理解错的话,你可以随心所欲。这个想法是在 PartyTypeId, Id.

上创建一个唯一的键
CREATE TABLE dbo.[User] (
    ID int NOT NULL,
    Name varchar(50) NOT NULL,
    PartyTypeId as cast(1 as tinyint) persisted,
    foreign key (ID, PartyTypeId) references Party(PartyID, PartyTypeID),
    unique (PartyTypeId, Id)
);

CREATE TABLE Stuff (
    StuffId int not null primary key,
    UserId int,
    PartyTypeId as cast(1 as tinyint)  persisted,
    Foreign Key (UserId) references user(PartyTypeId, userId)
);

Here 是一个 SQL Fiddle。 documentation.

中对此进行了解释

是的,你可以在 Stuff 引用中有一个外键,只是 User:

CREATE TABLE Stuff (
    StuffId int not null primary key,
    UserId int,
    Foreign Key (UserId) references dbo.[User](ID)
);