我正在使用 Microsoft SQL Server:
create database BOOKSTORE
use BOOKSTORE
create table Category
(
categoryID char(10) not null primary key,
name varchar(100)
);
create table Books
(
bookID char(10) not null primary key,
categoryID char(10) foreign key references Category(categoryID),
title varchar(100),
totalPages int,
isNew bit,
price decimal(6,2)
);
create table Orders
(
orderID char(10) not null primary key,
date_ordered date,
date_delivered date
);
create table Order_details
(
orderID char(10) foreign key references Orders(orderID),
productID char(10) foreign key references Books(bookID),
price decimal(6,2),
quantity int,
discount decimal(2,0)
constraint fk_orderPrice
foreign key(price) references Books(price)
);
我一直在寻找解决方案,但似乎没有这样的解决方案:SQL Server 一直说:
引用的表“Books”中没有与外键“fk_orderPrice”中的引用列列表匹配的主键或候选键。”
自从我从链接中了解到“将非主或非唯一设置为外键表明您的设计不是正常形式”: 如何设置非主或非唯一作为外键 我认为我正在处理的数据库一定有问题。
但是这个链接中的答案是: 向产品和 order_details 表添加价格字段 说“您在 Order_details 中的价格字段完全没问题”
你能告诉我我错在哪里吗?
问题是您试图在此处建立的 FK“参考”:
create table Order_details
(
orderID char(10) foreign key references Orders(orderID),
productID char(10) foreign key references Books(bookID),
....
constraint fk_orderPrice
foreign key(price) references Books(price)
);
您正在尝试引用
Books
- 但您可以仅引用表的主键(在SQL Server中还可以引用任何唯一列) - 但price
中的列Books
是这些都不是......
您需要创建对
Books.bookID
(Books
的主键)的引用,或者您需要在Books
中创建一些其他列(或列的组合),您可以使其唯一,以便它可以被参考; price
作为外键引用的列确实不是一个好主意......