我创建了三个表:
CREATE TABLE guest(
name varchar(100),
ranking int,
PRIMARY KEY (name)
);
CREATE TABLE room(
roomname varchar(100),
wallcolor varchar(100),
rating int,
PRIMARY KEY(roomnane)
);
CREATE TABLE reservation(
name varchar(100),
roomname varchar(100),
day varchar(100),
moveinday int,
moveoutday int,
PRIMARY KEY(roomname, day, start, finish),
FOREIGN KEY(roomname) REFERENCES room(roomname),
FOREIGN KEY(name) REFERENCES guest(name)
);
我正在尝试编写DELETE查询以删除所有不符合租房资格的客人。有资格租赁意味着客人排名大于或等于房间排名。
我试过
DELETE FROM guest, reservations
WHERE guest.ranking< rooms.ranking
这似乎违反了从预订到来宾表的参照完整性。我怎么能解决这个问题?
答案 0 :(得分:0)
tchelidze突出显示了一个案例:
假设客人1的排名低于room1,但高于room2。如果 删除guest1后,将违反参照完整性 预订表(适用于room2 guest1行)。
我认为你不应该删除访客条目。因为该特定客人可能有其他有效的预订。
[因此,如果您删除该访客,您可能会失去潜在客户。很大的损失! :P]
您应该删除违反标准的相应预订条目,而不是删除访客。
这就是我想要做的事。
我将删除客人排名低于客房排名的所有预订,但不会删除客人本身。
所以这是查询:
DELETE reservation
FROM
reservation
INNER JOIN (
SELECT
reservation.roomname,
reservation.day,
reservation.start,
reservation.finish
FROM
guest
INNER JOIN reservation ON reservation.name = guest.name
INNER JOIN room ON reservation.roomname = room.roomname
WHERE
room.rating > guest.ranking
) invalidReservationTable
ON reservation.roomname = invalidReservationTable.roomname
AND reservation.day = invalidReservationTable.day
AND reservation.start = invalidReservationTable.start
AND reservation.finish = invalidReservationTable.finish
<强>解释强>