我正在使用MySQL 5.0.95。我有一个网络表单,客户可以在其中为他们的活动创建一个客人名单,客人名单将由办公室经理批准,前台可以获得当天批准的访客。
为了节省空间,我把问题解决了。我有两个表,_events和_guests。我还有两个匹配的归档表。
CREATE TABLE IF NOT EXISTS visitor._events (
eventId int( 11 ) NOT NULL AUTO_INCREMENT,
eventName varchar( 200 ) NOT NULL,
PRIMARY KEY ( eventId )
);
CREATE TABLE IF NOT EXISTS visitor._archived_events (
eventId int( 11 ) NOT NULL,
eventName varchar( 200 ) NOT NULL,
PRIMARY KEY ( eventId )
);
CREATE TABLE IF NOT EXISTS visitor._guests (
guestId int( 11 ) NOT NULL AUTO_INCREMENT,
eventId int( 11 ) NOT NULL,
guestName varchar( 200 ) NOT NULL,
PRIMARY KEY ( guestId )
);
CREATE TABLE IF NOT EXISTS visitor._archived_guests (
guestId int( 11 ) NOT NULL,
eventId int( 11 ) NOT NULL,
guestName varchar( 200 ) NOT NULL,
PRIMARY KEY ( guestId )
);
我希望办公室经理能够在事件结束后从数据库中删除事件(及其访客记录),但我希望这些事件在一年中存档以进行记录管理。
我创建了一个TRIGGER,它会将_guests表中的任何记录DELETED复制到_archive_guests表中。
DELIMITER $$
DROP TRIGGER IF EXISTS TR_A_DEL_guests $$
CREATE TRIGGER TR_A_DEL_guests DELETE ON _guests FOR EACH ROW BEGIN
INSERT IGNORE INTO _archived_guests (
guestId,
guestName
) VALUES (
OLD.guestId,
guestName
);
END $$
DELIMITER ;
我还有一个TRIGGER,它将从_guests表中删除特定eventID的所有访客记录,然后将_events表中的任何DELETED记录复制到_archived_events表中。
DELIMITER $$
DROP TRIGGER IF EXISTS TR_A_DEL_events $$
CREATE TRIGGER TR_A_DEL_events AFTER DELETE ON _events FOR EACH ROW BEGIN
DELETE FROM _guests WHERE eventId = OLD.eventId;
INSERT IGNORE INTO _archived_events (
eventId,
eventName
) VALUES (
OLD.idEventId,
OLD.eventName
);
END $$
DELIMITER ;
结果是,当从_events中删除记录时,会将其移至_archived_events,并将该事件的所有_guests记录复制到_archived_guests表。
我遇到的问题是,现在,当客户正在编辑其访客列表时,如果他们删除访客记录,则会将其存档。他们可以编辑/删除访客,但不能完全删除该事件。
我的问题: 是否有任何方法只对已删除的事件使用一个TRIGGER,这些事件将首先将相应_guest记录的每个(eventId = OLD.eventId)复制到_archived_guests,然后将_event记录复制到_archived_events?
答案 0 :(得分:2)
如果我理解你正确的尝试
DELIMITER $$
DROP TRIGGER IF EXISTS TR_A_DEL_events_guests $$
CREATE TRIGGER TR_A_DEL_events_guests
BEFORE DELETE ON _events
FOR EACH ROW
BEGIN
-- Archive guests
INSERT IGNORE INTO _archived_guests (guestId, eventId, guestName)
SELECT guestId, eventId, guestName
FROM _guests
WHERE eventId = OLD.eventId;
-- Delete guests
DELETE
FROM _guests
WHERE eventId = OLD.eventId;
-- Archive event before deleting
INSERT IGNORE INTO _archived_events (eventId, eventName)
VALUES (OLD.eventId, OLD.eventName);
END $$
DELIMITER ;
这是 SQLFiddle 演示