表上的外键可以作为主键使用三个不同的表(每个表的主键数据都不同吗?

问题描述 投票:0回答:2

我有一个提醒表(ParentId)-从Product到ProductId的外键,从Order表到OrderId的外键。可能吗?当我尝试插入属于OrderId的Reminder表的数据时,出现外键约束错误。

Reminder
 - ReminderId
 - ParentId

Product
 - ProductId

Order
 - OrderId

ALTER TABLE [dbo].[Reminder]  WITH NOCHECK ADD  CONSTRAINT [FK_Reminder_ProductId] FOREIGN KEY([ParentId])

REFERENCES [dbo].[Product] ([ProductId])
GO

ALTER TABLE [dbo].[Reminder] NOCHECK CONSTRAINT [FK_Reminder_ProductId]
GO

ALTER TABLE [dbo].[Reminder]  WITH NOCHECK ADD  CONSTRAINT [FK_Reminder_OrderId] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Quote] ([QuoteId])
GO

ALTER TABLE [dbo].[Reminder] NOCHECK CONSTRAINT [FK_Reminder_OrderId]
GO
sql sql-server foreign-keys primary-key
2个回答
0
投票

如果我理解您的问题,那么不,这在我所知道的任何SQL数据库中都是不可能的。

我相信您要声明ParentId中的值必须出现在任一产品表(ProductId字段)或报价表(QuoteId字段)中。这在主/外键关系中是不允许的-您可以指向外键和一个,也只能指向一个主键。


0
投票

您可以使用外键关系和计算列来完成一些工作。这确实需要表中某种类型的“类型”:

create table reminders (
    ReminderId . . . primary key,
    parentId int, -- presumably
    type varchar(255),
    check (type in ('product', 'order')),
    parent_productid as (case when type = 'product' then parentId end) persisted,
    parent_orderid as (case when type = 'order' then parentId end) persisted,
    foreign key (parent_productid) references products(productId),
    foreign key (parent_orderid) references orders(orderid)
);
© www.soinside.com 2019 - 2024. All rights reserved.