首页  >  问答  >  正文

如果删除了行,则触发将其插入到另一个表中

我正在尝试创建一个触发器,将已删除的一行复制到另一个表中。到目前为止,当我删除一行时,我只是将整个第一个表复制到第二个表中,这不是很有用。

表1是带有comment_id、file_id、user_id、comment_text、comment_datetime和parent的评论

表2是comment_log,其中包含deleted_comment_id、file_id、user_id、comment_text、comment_datetime和comment_deletion_datetime。

所以我只想将用户、版主或管理员删除的评论存储在comment_log中。

INSERT INTO comment_log(deleted_comment_id, file_id, user_id, comment_text,comment_datetime, comment_deletion_datetime)
SELECT comment.comment_id, file_id, user_id, comment_text, comment_datetime, CURRENT_TIMESTAMP
FROM comment

这是我到目前为止所得到的,我已经尝试过像后面的 WHERE 之类的东西,但我不知道要放在那里。 old.comment_id 应该给我旧的 id,但我不知道如何从评论表中获取具有该 id 的评论。

P粉741223880P粉741223880241 天前329

全部回复(1)我来回复

  • P粉546138344

    P粉5461383442024-02-22 12:38:58

    被删除的行的列在触发器中可用作为 OLD.*,所以我会这样做:

    INSERT INTO comment_log
    SET deleted_comment_id = OLD.comment_id, 
        file_id = OLD.file_id, 
        user_id = OLD.user_id,
        comment_text = OLD.comment_text,
        comment_datetime = OLD.comment_datetime, 
        comment_deletion_datetime = CURRENT_TIMESTAMP;

    回复
    0
  • 取消回复