【问题标题】:Add Foreign Key that is part of primary key in the reference table?添加作为参考表中主键一部分的外键?
【发布时间】:2018-09-11 02:17:32
【问题描述】:

当引用表中的主键是两个字段时,如何添加外键。 在讲师给出的 ERD 图中,它显示表 product 中的两个字段(maker 和 model)都充当主键。 另一方面,在 DSD 图中,它显示了“PC”表中的字段模型是该表的主键,也是引用表产品中字段模型的外键。

当尝试在 SQL Server 中执行下面的代码时,会出现错误:

Msg 1774, Level 16, State 0, Line 10 外键'FK__PC__model__66603565'的引用列列表确实 与引用表“产品”中的主键不匹配。 消息 1750,级别 16,状态 1,第 10 行无法创建约束或 指数。查看以前的错误。

create table Product(
maker nvarchar(50) not null , 
model int not null ,
type nvarchar(50) not null,
CONSTRAINT PK_MAKER_MODEL PRIMARY KEY (maker,model),
CONSTRAINT CH_TYPE  check(type in ('PC','LAPTOP','PRINTER'))
)

-------------------------------------------------------------
create table PC(
model int not null ,
speed nvarchar(50),
ram nvarchar(50),
hd nvarchar(50),
price dec(12,2),
FOREIGN KEY ( model) REFERENCES Product
ON DELETE NO ACTION
)

DSD DIAGRAM ERD DIAGRAM

【问题讨论】:

标签: sql sql-server


【解决方案1】:

您不了解外键的工作原理。他们需要引用整个主键。出于这个原因,我更喜欢单列外键。更像是这样的:

create table Products (
    productId int identity(1, 1) primary key,
    maker nvarchar(50) not null, 
    model int not null,
    type nvarchar(50) not null,
    constraint unq_products_maker_model unique (maker, model),
    constraint chk_products_typecheck (type in ('PC', 'LAPTOP', 'PRINTER'))
);

create table PC (
    pcId int identity(1, 1) primary key,
    productId int not null,
    speed nvarchar(50),
    ram nvarchar(50),
    hd nvarchar(50),
    price dec(12,2),
    foreign key (productId) references Products(productId) on delete no action
);

【讨论】:

  • 如果给定的 ERD 图显示表 products 中的两个字段(制造商和模型)充当表的主键,是否会接受此解决方案?
  • @MarounNasra 。 . .我更喜欢合成密钥。这两列一起是候选主键,通过将它们声明为 not nullunique,您将获得基本相同的行为。
  • 我也更喜欢这个。我想我会这样做,它更容易理解。感谢您的宝贵时间
猜你喜欢
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
相关资源
最近更新 更多