如何在SQL中合并约束CHECK?
How to combine constraint CHECK in SQL?
下面有一个table:
CREATE TABLE LectureHalls
(
id SERIAL PRIMARY KEY,
floor INTEGER CHECK (floor <= 4),
classroom INTEGER NOT NULL,
CONSTRAINT sc_unique_lectureHall UNIQUE (id, floor, classroom),
CONSTRAINT sc_unique_lectureHall2 UNIQUE (floor, classroom);
);
是否可以在 sql 中创建这样的约束,以便当 floor = 1 classroom> 0 且 classroom <= 30 时?
这是你想要的吗?
create table lecturehalls (
id serial primary key,
floor integer check (floor <= 4),
classroom integer not null,
unique (floor, classroom),
check(floor is distinct from 1 or (classroom > 0 and classroom <= 30))
);
请注意,我删除了 (id, floor, classroom)
上的唯一约束:id
是 table 的主键,因此无论如何这是一个 no-op。
您可以:
CREATE TABLE LectureHalls
(
id SERIAL PRIMARY KEY,
floor INTEGER NOT NULL CHECK (floor BETWEEN 1 AND 4),
classroom INTEGER NOT NULL,
UNIQUE KEY (floor, classroom),
CHECK (floor = 1 AND classroom BETWEEN 1 AND 30)
);
此表格允许扩展到更多楼层:
CREATE TABLE LectureHalls
(
id SERIAL PRIMARY KEY,
floor INTEGER NOT NULL CHECK (floor BETWEEN 1 AND 4),
classroom INTEGER NOT NULL,
UNIQUE KEY (floor, classroom),
CHECK (floor = 1 AND classroom BETWEEN 1 AND 30 OR
floor = 2 AND classroom BETWEEN 1 AND 15 OR
floor = 3 AND classroom BETWEEN 1 and 24)
);
下面有一个table:
CREATE TABLE LectureHalls
(
id SERIAL PRIMARY KEY,
floor INTEGER CHECK (floor <= 4),
classroom INTEGER NOT NULL,
CONSTRAINT sc_unique_lectureHall UNIQUE (id, floor, classroom),
CONSTRAINT sc_unique_lectureHall2 UNIQUE (floor, classroom);
);
是否可以在 sql 中创建这样的约束,以便当 floor = 1 classroom> 0 且 classroom <= 30 时?
这是你想要的吗?
create table lecturehalls (
id serial primary key,
floor integer check (floor <= 4),
classroom integer not null,
unique (floor, classroom),
check(floor is distinct from 1 or (classroom > 0 and classroom <= 30))
);
请注意,我删除了 (id, floor, classroom)
上的唯一约束:id
是 table 的主键,因此无论如何这是一个 no-op。
您可以:
CREATE TABLE LectureHalls
(
id SERIAL PRIMARY KEY,
floor INTEGER NOT NULL CHECK (floor BETWEEN 1 AND 4),
classroom INTEGER NOT NULL,
UNIQUE KEY (floor, classroom),
CHECK (floor = 1 AND classroom BETWEEN 1 AND 30)
);
此表格允许扩展到更多楼层:
CREATE TABLE LectureHalls
(
id SERIAL PRIMARY KEY,
floor INTEGER NOT NULL CHECK (floor BETWEEN 1 AND 4),
classroom INTEGER NOT NULL,
UNIQUE KEY (floor, classroom),
CHECK (floor = 1 AND classroom BETWEEN 1 AND 30 OR
floor = 2 AND classroom BETWEEN 1 AND 15 OR
floor = 3 AND classroom BETWEEN 1 and 24)
);