我正在为酒店预订创建一个项目,我想在有主键列的表中作为外键的列中插入多个值,但当它是主键时,不可能插入重复的键,也不可能插入与我在该表中将其用作外键的主列中插入的值不同的值,那我该怎么办?
澄清
我有一个用于预订的表和另一个用于酒店服务的表,[Reservation]
表中有一列是主键(ReservationID
(,[Hotel_Services]
表中有列我用作[Reservation]
表的外键(ServiceID
(。
我想要的是在每个预订中插入多个服务ID,以指示每位客人已添加到其预订中的服务,我该如何做到这一点?
表1:Reservation
`ReservationID` (primary key) e.g 10,20,30
表2:Hotel_Services
`ServiceID` (foreign key to `Reservations`) e.g 1, 2, 3
期望的结果:在每个预订中添加多个服务ID例如:
Reservation 10 has 1,2 services
Reservation 20 has 1,3 services
Reservation 30 has 2,3 services
您需要一个ReservationServices
表,定义如下:
create table ReservationServices (
ReservationServiceId int identity primary key,
ReservationId int not null references reservations(reservationid),
ServiceId int not null references services(serviceid);
);
然后你的数据看起来像:
ReservationServiceId ReservationId ServiceId
1 10 1
2 10 2
3 20 1
4 20 3
. . .
因此,为预订插入一个新服务就像在这个表中插入一个新行一样简单。