在 MySQL 中模拟 DELETE CASCADE? [英] Simulate a DELETE CASCADE in MySQL?
问题描述
是否可以自动预测 DELETE CASCADE 之后的操作?在我的软件中,我想向用户发出警告,其中包含有关将被删除的数据的详细信息.
Is it possible to predict the operations that follow a DELETE CASCADE automatically? In my software I would like to give the user a warning with details about the data that would be deleted then.
推荐答案
您可以制作数据库的副本并将触发器放在删除后
You can make a copy of the database and put triggers on the after delete
DELIMITER $$
CREATE TRIGGER ad_table1_each AFTER DELETE ON table1 FOR EACH ROW
BEGIN
INSERT INTO log VALUES (null /*autoinc id*/
, 'table1' /*tablename*/
, old.id /*tableid*/
, concat_ws(',',old.field1,old.field2 /*CSV's of fields*/
, NOW() /*timestamp*/
, 'delete'); /*what action*/
REPLACE INTO restore_table1 VALUES (old.id,
, old.field1
, old.field2
, ... );
END $$
DELIMITER ;
日志表只是一个包含以下字段的表:
The log table is just a table with the following fields:
id integer autoincrement primary key
tablename varchar(45)
table_id integer
fields varchar(6000)
delete_time timestamp
action enum('insert','update','delete')
如果在副本的删除级联之前执行 SELECT @last_id:= max(id) FROM log
.
然后你可以做一个 SELECT * FROM log WHERE id >@last_id
并获取将在级联中删除的所有行.
If you do a SELECT @last_id:= max(id) FROM log
before the delete cascade on the copy.
Then you can do a SELECT * FROM log WHERE id > @last_id
and get all the rows that will be deleted in the cascade.
之后,您可以使用restore_table1 在副本数据库中重新创建在级联中删除的行.
After that you can use the restore_table1 to recreate the rows that were deleted in the cascade in the copy database.
这篇关于在 MySQL 中模拟 DELETE CASCADE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!