如何使用其他连接表中的记录存档记录?

时间:2009-08-27 15:14:04

标签: mysql triggers

我有8张桌子:

users:
  uid
users_removed:
  uid
messages:
  mid
  uid FK users (uid)
messages_removed:
  mid
  uid
comments:
  cid
  mid FK messages (mid)
comments_removed:
  cid
  mid
files:
  fid
  mid FK messages (mid)
files_removed:
  fid
  mid

当我从表“users”中删除记录时,我想将其移至table users_removed(在从用户删除之前)。我还想要将所有相应的消息(以及文件和注释)移动到* _removed表。

我使用了触发器:

CREATE TRIGGER delete_user BEFORE DELETE ON users
    FOR EACH ROW BEGIN
        INSERT IGNORE INTO users_removed
            SELECT * FROM users WHERE uid = OLD.uid;
        DELETE FROM messages WHERE OLD.uid in (owner_id, author_id);
    END
|

CREATE TRIGGER delete_message BEFORE DELETE ON messages
    FOR EACH ROW BEGIN
        INSERT IGNORE INTO messages_removed
            SELECT * FROM messages WHERE mid = OLD.mid;
        DELETE FROM comments WHERE mid = OLD.mid;
        DELETE FROM files WHERE mid = OLD.mid;
    END
|

CREATE TRIGGER delete_comment BEFORE DELETE ON comments
    FOR EACH ROW BEGIN
        INSERT IGNORE INTO comments_removed
            SELECT * FROM comments WHERE cid = OLD.cid;
    END
|

CREATE TRIGGER delete_file BEFORE DELETE ON files
    FOR EACH ROW BEGIN
        INSERT IGNORE INTO files_removed
            SELECT * FROM files WHERE fid = OLD.fid;
    END
|

但是>它的工作速度非常慢50k用户,> 1m消息,评论和文件。

有没有快速的方法呢?

1 个答案:

答案 0 :(得分:1)

  1. 没有快速的方法可以做到这一点。假设您正在使用InnoDB,您必须编写一个表条目,删除一个表条目引用,然后InnoDB进行第二次清理运行以实际摆脱它(删除是昂贵的)。然后,随着时间的推移删除更多用户,在数据库中出现这些漏洞几乎肯定会最终损害性能。

  2. 如果您要保存用户信息,为什么不直接使用enum(true,false)向名为“active”的users表添加一列?