【问题标题】:MySQL Insert and Update trigger issueMySQL插入和更新触发器问题
【发布时间】:2013-04-09 18:03:07
【问题描述】:

我试图通过分别捕获插入和更新的用户 ID 和时间戳来实现行级审计。但是由于某种原因,即使更新也会触发插入触发器,并且每次都会更新两个 insert_* 列(对于更新也是如此)。 请帮忙。

表格

create table test
(id varchar(30) primary key,
insert_id varchar(30),
insert_timestamp timestamp, 
update_id varchar(30), 
update_timestamp timestamp);

在插入触发器之前

 DELIMITER //
    create trigger ins_test 
    before insert on test 
    for each row 
    Begin
    set new.insert_id = session_user();
    set new.insert_timestamp = now();
    End;
    //

更新前触发器

  DELIMITER //
    create trigger upd_test 
    before update on test 
    for each row 
    Begin
    set new.update_id = session_user();
    set new.update_timestamp = now();
    End;
    //

-甘尼什

【问题讨论】:

    标签: mysql triggers


    【解决方案1】:

    我在 SQL Fiddle 中的 MySQL 5.5.30 中尝试了您的代码,并且触发器正常工作。

    如果您不希望它们在插入时默认为 current_timestamp,则应将时间戳列明确定义为 NULL:

    create table test
    (
      id varchar(30) primary key,
      insert_id varchar(30) null,
      insert_timestamp timestamp null, 
      update_id varchar(30) null, 
      update_timestamp timestamp null
    );
    

    试试这个SQL Fiddle 看看你的触发器是否正常工作。我在每个语句之间添加了 1 秒的睡眠时间,这样您就可以知道 insert_timestamp 在更新时不会改变。

    【讨论】:

    • 谢谢!将时间戳列定义为 NULL 有效。
    猜你喜欢
    • 1970-01-01
    • 2016-10-13
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多