如果标题不完全有用,我很抱歉,但我不确定如何在标题中解释我的问题。
所以基本上,我想创建一个这样的表:
预订
day
room
id_client
[other_stuff]
对于给定的一天+房间,您可以获得id_client +其他所有内容。而且对于给定的id_client +日,您可以获得房间+其他东西。
我不明白我怎么说复合日+房间必须是唯一的,复合日+ id_client也必须是唯一的。我真的需要在我的数据库中使用这两种约束。
有人有想法吗?
感谢。
答案 0 :(得分:4)
将PRIMARY KEY
和另一个组合定义为UNIQUE
键:
CREATE TABLE reservation
( day
, room
, id_client
, [other_stuff]
, PRIMARY KEY (day, room)
, UNIQUE KEY (id_client, day)
) ;
或者相反:
CREATE TABLE reservation
( day
, room
, id_client
, [other_stuff]
, PRIMARY KEY (id_client, day)
, UNIQUE KEY (day, room)
) ;
或者,如果您已有另一个主键,请将它们设为唯一:
CREATE TABLE reservation
( reservation_id
, day
, room
, id_client
, [other_stuff]
, PRIMARY KEY (reservation_id)
, UNIQUE KEY (id_client, day)
, UNIQUE KEY (day, room)
) ;
答案 1 :(得分:1)
-- in MySQL
drop database if exists mydatabase;
create database mydatabase;
use mydatabase;
drop table if exists client;
create table client
(
id int unsigned not null auto_increment,
name varchar(45) not null,
primary key (id)
)engine=InnoDB default charset=utf8;
drop table if exists room;
create table room
(
id int unsigned not null auto_increment,
label varchar(45) not null,
primary key (id)
)engine=InnoDB default charset=utf8;
drop table if exists reservation;
create table reservation
(
id int unsigned not null auto_increment,
id_room int unsigned,
id_client int unsigned,
day date,
unique(day, id_room),
unique(day, id_client),
foreign key (id_room) references room(id),
foreign key (id_client) references client(id),
primary key (id)
)engine=InnoDB default charset=utf8;
答案 2 :(得分:0)
有两种方式可以看待这种情况......您提到的独特限制是否相互排斥?意思是,一个人可以不存在吗?
逻辑规定,无论客户如何,房间都可以一次预订一天。除非多个客户可以共享同一个房间。所以我会给你两个选择。
# If room can be booked to multiple clients
CREATE TABLE `reservation` (
`id` int(11) unsigned not null auto_increment,
`day` varchar(25) not null,
`room` int(5) unsigned not null,
`id_client` int(11) unsigned not null,
PRIMARY KEY (`id`),
UNIQUE KEY (`room`, `day`),
UNIQUE KEY (`room`, `id_client`),
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Room can only be booked to one client for a given day
CREATE TABLE `reservation` (
`id` int(11) unsigned not null auto_increment,
`day` varchar(25) not null,
`room` int(5) unsigned not null,
`id_client` int(11) unsigned not null,
PRIMARY KEY (`id`),
UNIQUE KEY (`room`, `day`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
另外,我会使用单独的主键列,否则您的更新会更复杂,例如:
UPDATE `reservation` SET `other_stuff` = 'some value' WHERE `day` = 'Friday' AND `room` = 123;
# Vs
UPDATE `reservation` SET `other_stuff` = 'some value' WHERE `id` = 1;