为什么我的外键约束不起作用?

时间:2014-01-09 14:25:27

标签: sql sql-server database

/*Create Purchased Products Table*/
create table Purchased_Products
(
School_ID INT not null,
Product_ID INT not null,
Purchased_Product_ID INT IDENTITY (1,1) not null,
Quantity INT,
Product_Status VARCHAR(1)

  constraint Purchased_Products_PK PRIMARY KEY (School_ID, Product_ID, Purchased_Product_ID),
  constraint Purchased_Products_FK1 FOREIGN KEY (School_ID) REFERENCES School(School_ID),
  constraint Purchased_Products_FK2 FOREIGN KEY (Product_ID) REFERENCES Product(Product_ID)
);

create table Credentials
(
Credential_ID INT IDENTITY (1,1) not null,
Purchased_Product_ID INT not null,
Username VARCHAR (30),
PPassword VARCHAR (30),
URL VARCHAR (100),
Remote_Username VARCHAR (30),
Remote_Password VARCHAR (30),
Remote_URL VARCHAR (100),
Notes VARCHAR (200),

  constraint Credentials_PK PRIMARY KEY (Credential_ID, Purchased_Product_ID),
  constraint Credentials_FK FOREIGN KEY (Purchased_Product_ID) REFERENCES Purchased_Products(Purchased_Product_ID)

);

好的,所以我想创建这个表,Credentials,但它给了我错误:

Msg 1776,Level 16,State 0,Line 1 引用的表'Purchased_Products'中没有与外键'Credentials_FK'中的引用列列表匹配的主键或候选键。 Msg 1750,Level 16,State 0,Line 1 无法创建约束。查看以前的错误。

它似乎允许我这样做,但我想不出我在做什么。也许我忽略了什么?帮助?? !! ??

2 个答案:

答案 0 :(得分:2)

Purchased_Products.Purchased_Product_ID需要显式为UNIQUE或显式主键,才能使其成为外键的参考列。

CREATE UNIQUE NONCLUSTERED INDEX IndexName 
ON Purchased_Products(Purchased_Product_ID)

如果索引中有多个列,则创建唯一索引会对列(或列集)强制执行唯一性,SQL将允许您将其用作外键的引用。

答案 1 :(得分:0)

外键只能在具有UNIQUE coumns的列上创建,例如主键或唯一索引。

Purchased_Products目前只有一个唯一约束,即复合PK:

constraint Purchased_Products_PK 
   PRIMARY KEY (School_ID, Product_ID, Purchased_Product_ID)

Credentials正试图仅在其中一列上强制执行外键,即

constraint Credentials_FK 
  FOREIGN KEY (Purchased_Product_ID) 
  REFERENCES Purchased_Products(Purchased_Product_ID)

从技术上讲,您需要重复Credentials中的所有复合键列(即School_IDProduct_IDPurchased_Product_ID)并在这些列上创建复合外键。

但是,您的表格设计似乎有问题 - 您选择Primary Keys似乎很不幸,例如Purchased_Products有一个简单代理主键的候选者:

Purchased_Product_ID INT IDENTITY (1,1) not null

同样对于Credentials,鉴于Credential_IDidentity已唯一,因此无需向PK添加Purchased_Product_ID。你可能想要的是:

Table : Products
Primary Key : ProductId

Table : Purchased_Products
Primary Key : Purchased_Product_ID
Foreign Key : ProductID references Products(ProductId)

Table : Credentials
Primary Key : Credential_ID
Foreign Key : Purchased_Product_ID references Purchased_Products(Purchased_Product_ID)