Mysql trigger usage examples

Mysql trigger usage examples

1 description

Record the data and update time of the user table

2 code implementation

2.1 Table

original table

CREATE TABLE `t_user` (
  `user_id` int(4) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`user_id`)
);

Record Form

CREATE TABLE `t_user_record` (
  `user_id` int(4) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `update_time` bigint not null,
  PRIMARY KEY (`user_id`)
);

2.2 Trigger

#DELIMITER $
CREATE TRIGGER user_record_trigger AFTER INSERT ON t_user FOR EACH ROW
BEGIN
    INSERT INTO t_user_record(`user_id`, `user_name`, `password`, `update_time`) values(NEW.`user_id`, NEW.`user_name`, NEW.`password`, unix_timestamp()) 
    on DUPLICATE key update `user_name`= values(`user_name`), `password`= values (`password`), `update_time`=unix_timestamp(); 
END #$
#DELIMITER;

3. Execution results

3.1 Original table data

Add a new piece of data (user_id=4)
Insert image description here

3.2 Record table data

The corresponding records are generated by triggers in the record table
Insert image description here

Guess you like

Origin blog.csdn.net/pp_lan/article/details/128950223