这是我的第一个数据库,我创建了HOTEL
,ROOM
和GUEST
表,但是当我执行BOOKING
表时,它不起作用。
错误是:
引用表'
ROOM
'中没有主键或候选键 与外键中的引用列列表匹配 'FK_BOOKING_ROOM
'
脚本:
CREATE DATABASE HOTEL
USE HOTEL
CREATE TABLE HOTEL
(
HolCode varchar(20) UNIQUE NOT NULL,
Name varchar(30),
City varchar(20) DEFAULT 'Ha noi',
CONSTRAINT PK_HOLEL PRIMARY KEY (HolCode)
)
CREATE TABLE ROOM
(
RoomNo int,
HolCode varchar(20),
TypeRoom char(1) DEFAULT 'S',
Price double precision,
CONSTRAINT CHK_TYPE CHECK (TypeRoom = 'D' OR TypeRoom = 'S' OR TypeRoom = 'F'),
CONSTRAINT CHK_PRICE CHECK (10 <= Price AND Price <= 200),
CONSTRAINT PK_ROOM PRIMARY KEY (RoomNo, HolCode),
CONSTRAINT FK_ROOM FOREIGN KEY (HolCode) REFERENCES HOTEL(HolCode)
)
-- TAO BANG GUEST
CREATE TABLE GUEST
(
GuestNo int,
GuestName varchar(30),
Address varchar(50),
CONSTRAINT PK_GUEST PRIMARY KEY (GuestNo)
)
--TAO BANG BOOKING
CREATE TABLE BOOKING
(
HolNo varchar(20) NOT NULL,
GuestNo int NOT NULL,
DateFrom DateTime DEFAULT GETDATE(),
DateTo DateTime,
RoomNo int NOT NULL,
CONSTRAINT PK_BOOKING PRIMARY KEY (HolNo, DateFrom, RoomNo),
-- CONSTRAINT FK_BOOKING_HOTEL FOREIGN KEY (HolNo) REFERENCES HOTEL(Code),
CONSTRAINT FK_BOOKING_GUEST FOREIGN KEY (GuestNo) REFERENCES GUEST(GuestNo),
CONSTRAINT FK_BOOKING_ROOM FOREIGN KEY (RoomNo, HolCode)
REFERENCES ROOM(RoomNo, HolCode)
)
DROP TABLE BOOKING
答案 0 :(得分:2)
尝试:
CONSTRAINT FK_BOOKING_ROOM FOREIGN KEY (RoomNo,HolNo)
REFERENCES ROOM(RoomNo,HolCode)
客房不仅仅由RoomNo
标识,因此外键也需要拥有酒店代码。我还建议,作为一个风格点,您尝试在内容应该相同的每个表中使用相同的名称 - 所以HolNo
或HolCode
,但不是< EM>两个