我创建了三个表:
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 FROM guest, reservations
WHERE guest.ranking< rooms.ranking
这似乎违反了从预订到来宾表的引用完整性。我该怎么解决?
最佳答案
tchelidze强调了一个案例:
假设客人1的等级比房间1低,但比房间2高。如果
如果删除guest1,则引用完整性将在
预订表(适用于2号客房1行)。
我认为你不应该删除来宾条目。因为那个客人可能还有其他有效的预订。
[所以如果你删除了那个客人,你可能会失去你的潜在客户。损失惨重!: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
说明:
关于mysql - 如何使用DELETE并保持参照完整性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35124238/