对特定子类型

时间:2015-07-25 02:42:16

标签: sql sql-server relational-database supertype

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

说我有以下架构(改编自上面链接中的@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','用户'可以拥有许多'Stuff'项目,但是'Groups'拥有'Stuff'是没有意义的。我可以在'Stuff'引用中只有'用户'的外键吗?

如果有可能,那怎么会这样做呢?或者我是否必须直接通过'派对'来完成我的所有外键? 我收到了一个错误(当我自己尝试时,引用的表'dbo.Users'中没有与外键中的引用列'ID'匹配的主键或候选键

提前致谢!

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以做你想做的事。我们的想法是在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小提琴。 这在documentation

中有解释

答案 1 :(得分:0)

是的,您可以在Stuff参考中使用外键:User:

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