此处提出类似问题multiple foreign keys referencing single column in other table 但答案中没有显示语法。我想知道如何在SQL Server中实现这一点。以下语法提供错误
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemIssue_Person
FOREIGN KEY (PersonID, AdvisorID) REFERENCES Person (PersonID)
;
错误:外键中的引用列数与引用列数(表'ItemIssue')不同。
-- Create Tables
CREATE TABLE ItemIssue (
ItemIssueID int identity(1,1) NOT NULL,
PersonID int,
AdvisorID int,
)
;
CREATE TABLE Person (
PersonID int NOT NULL,
Name nvarchar(500),
)
答案 0 :(得分:2)
您需要定义两个外键,每列一个:
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemIssue_Person
FOREIGN KEY (PersonID) REFERENCES Person (PersonID)
;
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemAdvisor_Person
FOREIGN KEY (AdvisorID) REFERENCES Person (PersonID)
;
答案 1 :(得分:0)
无法为引用一列的两列创建一个外键。分开创建它们:
ALTER TABLE ItemIssue
ADD CONSTRAINT FK_ItemIssue_Person_Person FOREIGN KEY (PersonID) REFERENCES Person (PersonID),
ADD CONSTRAINT FK_ItemIssue_Advisor_Person FOREIGN KEY (AdvisorID) REFERENCES Person (PersonID);
答案 2 :(得分:0)
定义两个外键,每列一个 -
表
合同 - HospidPharmacyId专栏
Hospice-HospiceID PK Pharmacy PharmacyId Pk
更改表合约 添加约束fk_pharmacyID外键([HospIDPharmID])引用药房([PharmacyID])
改变合同 添加约束Fk_hospId外键([HospIDPharmID])引用临终关怀(HospiceID)
表。临终关怀和临终关怀不在药房,我们不能在
中插入该值 合同表&反之亦然。