例如我有这张表:
+-------------------+
| id |
| email |
| password |
| birthdate |
+-------------------+
值:
1:'test@test.com ':' 123456 ':' 1995年7月23日
我决定将id = 1的生日改为'1996-07-23'
所以,我想登录以下“历史”表:
table_name:'user',field_name:'birthdate',previous_value:'1995-07-23',new_value:'1996-07-23'
+-------------------+
| id |
| table_name |
| field_name |
| previous_value |
| new_value |
| history_datetime |
+-------------------+
有任何建议吗?
答案 0 :(得分:0)
你可以试试这个
CREATE TRIGGER user_update
AFTER UPDATE ON user
FOR EACH ROW
INSERT INTO history (obj_id, table_name, field_name, previous_value, new_value, history_datetime)
SELECT NEW.id, 'user', 'email', OLD.email, NEW.email, NOW()
FROM user
WHERE IFNULL(NEW.email, '') <> IFNULL(OLD.email, '')
UNION ALL
SELECT NEW.id, 'user', 'birthdate', OLD.birthdate, NEW.birthdate, NOW()
FROM user
WHERE IFNULL(NEW.birthdate,'') <> IFNULL(OLD.birthdate, '');
NULL
s。这是 SQLFiddle 演示
注意:历史记录表中的id
列生成了auto_increment,并引入了其他obj_id
列来引用正在记录的对象的id