You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

设置ProductID为外键时提示被引用表无匹配主键如何解决

问题原因

Products表的主键为复合主键(ProductID, CategoryID, SupplierID),SQL Server的外键约束要求:外键引用的列必须是被引用表的完整主键,或者具备唯一性约束的候选键。你在InventoryTransactions表中仅单独引用ProductID一列作为外键,不满足该规则,因此触发报错。
额外说明:后续InventoryTransactions表引用PurchaseOrderID作为外键时也会触发同类报错,因为PurchaseOrders表的主键同样是复合主键(PurchaseOrderID, EmpID),单独引用PurchaseOrderID也不符合规则。

解决方案

方案1(推荐):调整主键设计

自增列本身可以唯一标识表内的单行数据,不需要和其他列组合为复合主键,直接修改两张表的主键定义即可:

-- 修改Products表的主键定义
create table Products
(
    ProductID int not null identity(100,1),
    ProductCode nvarchar(25) not null,
    ProductName nvarchar(50) not null,
    Description nvarchar(1000) not null,
    CategoryID int not null,
    StandardCost money not null,
    ListPrice money not null,
    ReorderLevel int not null,
    TargetLevel int not null,
    Discontinued bit not null,
    SupplierID int not null,
    primary key (ProductID), -- 仅保留ProductID作为主键
    foreign key (CategoryID) references Category(CategoryID),
    foreign key (SupplierID) references Suppliers(SupplierID)
)
go

-- 修改PurchaseOrders表的主键定义
create table PurchaseOrders
(
    PurchaseOrderID int not null identity(500,1),
    CreationDate date not null,
    StatusID int not null,
    ExpectedDate date not null,
    ApprovedBy int,
    ApprovedDate date,
    EmpID int not null,
    primary key (PurchaseOrderID), -- 仅保留PurchaseOrderID作为主键
    foreign key (EmpID) references Employees(EmpID)
)
go

修改后原来的InventoryTransactions表的外键定义即可正常执行。

方案2(不推荐):保留复合主键,调整外键定义

如果业务要求必须保留现有复合主键设计,需要在InventoryTransactions表中新增对应字段,引用完整的复合主键:

create table InventoryTransactions
(
    TransactionID int not null identity(700,1),
    TransactionType int not null,
    CreatedDate datetime2(7) not null,
    ProductID int not null,
    CategoryID int not null, -- 新增字段,对应Products表的复合主键列
    SupplierID int not null, -- 新增字段,对应Products表的复合主键列
    Quantity int not null,
    PurchaseOrderID int not null,
    EmpID int not null, -- 新增字段,对应PurchaseOrders表的复合主键列
    CustomerOrderID int not null,
    Comments nvarchar(1000) not null,
    primary key (TransactionID, ProductID, PurchaseOrderID),
    foreign key (ProductID, CategoryID, SupplierID) references Products(ProductID, CategoryID, SupplierID),
    foreign key (PurchaseOrderID, EmpID) references PurchaseOrders(PurchaseOrderID, EmpID)
)
go

该方案会增加冗余字段,仅建议有特殊业务需求时使用。

内容的提问来源于stack exchange,提问作者Connor Wells

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:24:03