CREATE TABLE hotel_reservation(
hotel_code VARCHAR2(5),
room_type VARCHAR2(75), CONSTRAINT check_room_type CHECK(room_type LIKE 'DELUXE' or room_type LIKE 'SUPERIOR' or room_type LIKE 'MASTERS SUITE') NOT NULL,
room_id number(3), CONSTRAINT fk_room_id FOREIGN KEY(room_id) REFERENCES rooms(room_id) NOT NULL
);
它一直说缺少右括号,但我没有看到任何遗漏。
答案 0 :(得分:2)
问题是最后的NOT NULL
。以下是表达此定义的一种方式:
CREATE TABLE hotel_reservation (
hotel_code VARCHAR2(5),
room_type VARCHAR2(75) NOT NULL,
CONSTRAINT check_room_type CHECK (room_type in ('DELUXE', 'SUPERIOR', 'MASTERS SUITE')),
room_id number(3) NOT NULL,
CONSTRAINT fk_room_id FOREIGN KEY (room_id) REFERENCES rooms(room_id)
);
我还将第一个check
约束更改为使用in
而不是or
。
答案 1 :(得分:1)
我更喜欢将约束保持在线外,或者 - 可能/有时甚至更好 - 来自CREATE TABLE脚本。为什么?如有必要,可以更轻松地重新创建它们。
一个选项:
CREATE TABLE hotel_reservation
(
hotel_code VARCHAR2 (5),
room_type VARCHAR2 (75) NOT NULL,
room_id NUMBER (3) NOT NULL,
--
CONSTRAINT check_room_type CHECK
( room_type LIKE 'DELUXE'
OR room_type LIKE 'SUPERIOR'
OR room_type LIKE 'MASTERS SUITE'),
CONSTRAINT fk_room_id FOREIGN KEY (room_id) REFERENCES rooms (room_id)
);
另一个:
CREATE TABLE hotel_reservation
(
hotel_code VARCHAR2 (5),
room_type VARCHAR2 (75) NOT NULL,
room_id NUMBER (3) NOT NULL
);
ALTER TABLE hotel_reservation ADD
CONSTRAINT check_room_type CHECK
( room_type LIKE 'DELUXE'
OR room_type LIKE 'SUPERIOR'
OR room_type LIKE 'MASTERS SUITE');
ALTER TABLE hotel_reservation ADD
CONSTRAINT fk_room_id FOREIGN KEY (room_id)
REFERENCES rooms (room_id);
答案 2 :(得分:1)
我更喜欢与列内联的单列约束,因为它是一种更紧凑的语法,您也可以让子表从父级继承其数据类型。
-- Parent table for demo purposes:
create table rooms
( room_id integer primary key );
create table hotel_reservation
( hotel_code varchar2(5) -- Probably this should be mandatory and a FK to hotels
, room_type varchar2(75) not null
constraint check_room_type check (room_type in ('DELUXE','SUPERIOR','MASTERS SUITE'))
, room_id not null constraint fk_room_id references rooms(room_id) );
注意hotel_reservation.room_id
从rooms.room_id
继承其数据类型。
答案 3 :(得分:0)
CREATE TABLE hotel_reservation( hotel_code VARCHAR(5), room_type VARCHAR(75),
room_id整数, CONSTRAINT fk_room_id FOREIGN KEY(room_id)REFERENCES rooms(room_id), CONSTRAINT check_room_type检查( room_type LIKE' DELUXE' 或room_type LIKE' SUPERIOR' 或room_type LIKE' MASTERS SUITE' ) );
NOT Null用于定义列。不适用于约束