Table 与单个主键有多个关系

Table with multiple relations to a single primary key

是否可以创建从一个 table 到另一个 table 的多个关系?

我有一个 table 包含购买,每个购买都有一个 origin_country 和一个 destination_country。 我想与来自同一 table.

的这两列中的 table 上的单个 PK 建立关系(作为外键)

我尝试了以下查询:

alter table Purchases
    add constraint FK_Purchases_OriginCountries
        foreign key (FK_OriginCountryCode) references dbo.countries

go

alter table Purchases
    add constraint FK_Purchases_DestinationCountries
        foreign key (FK_DestinationCountryCode) references dbo.countries
    
go

但最终发生了冲突,但是我找不到证明这是不可能的文档...

[23000][547] The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Purchases_DestinationCountries". The conflict occurred in database "Market", table "dbo.countries", column 'ID'.

这种关系是故意不可能的,还是我搞错了?

谢谢

是的,你可以。

错误不是尝试将两个外键创建回单个 table 的结果,这完全没问题。试试 运行 看看它是否有效:

create table t(i int primary key);

create table u
(
   j int foreign key references t(i),
   k int foreign key references t(i)
);

您遇到的问题是您的 Purchases table 中有一些数据,其中您尝试创建外键的列中的值在 countries table 的 ID 列。

要找到它们 运行 像这样的查询:

select  p.* 
from    dbo.purchases p 
where   not exists 
        (
           select *
           from   dbo.countries
           where  ID = p.FK_DestinationCountryCode
        )

请注意,我认为您的列名在这里有点奇怪,您不应该调用列 FK_DestinationCountryCode 只是因为它上面有外键,并且“代码”不是同一类事物作为“ID”。您的 purchases table 的专栏可能应该称为 DestinationCountryIDOriginCountryID.