一个table上的Foreign Key可以是三个不同的table作为主键吗(每个table主键数据不同)?

Can Foreign Key on a table be three different tables as primary keys (each table primary key data is different)?

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

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 数据库中都是不可能的。

我相信您想说明 ParentId 中的值必须出现在 产品 table(ProductId 字段)或报价 table 中(报价单字段)。这在主键/外键关系中是不允许的——您可以指向外键和一个,而且只有一个主键。

您可以做一些工作,使用外键关系和计算列。这确实需要 table:

中的某种 "type"
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)
);

Here 是一个 db<>fiddle.