SQL无法创建外键

时间:2017-12-16 08:32:20

标签: sql

我确定我的问题有点傻,但我无法解决。这是我的问题:

create table Product
(
    ProductID int PRIMARY KEY,
    ProductName varchar(16),
    RetrailPrice int,
    WholesalePrice int,
    MonthDelivery int,
    Waste int,
    StorageName varchar(16)
)

create table Storage
(
    StorageID int PRIMARY KEY,
    StorageName varchar(16),
    City varchar(16),
    Employees int,
    Area int,
    ProductID int
)

当然我想链接他们

alter table Product
    add FOREIGN KEY (StorageName) references Storage(StorageName)

但是我无法做到,我在某处错了:/

1 个答案:

答案 0 :(得分:1)

您必须从存储表中引用PK。对于FK,StorageName是一个糟糕的选择。如果不同城市中的存储名称相同,该怎么办?

使用StorageID

替换Product表中的StorageName
create table Product(
ProductID int PRIMARY KEY,
ProductName varchar(16),
RetrailPrice int,
WholesalePrice int,
MonthDelivery int,
Waste int,
StorageID int)   --this has chnaged, it will hold the id/PK of the Storage

create table Storage(
StorageID int PRIMARY KEY,
StorageName varchar(16),
City varchar(16),
Employees int,
Area int,
ProductID int)

然后:

alter table Product
add FOREIGN KEY (StorageID) references Storage(StorageID)