Mysql creates a trigger, and each time a piece of data is inserted, the column is automatically incremented

Database version: 5.2.70

Requirement: Use triggers to realize that every time a new piece of user data is added, the index column data of the user table is automatically incremented each time, so that a single column input is automatically incremented.

#1. 如果已存在触发器[tri_user_index]则删除
drop trigger IF EXISTS tri_user_index ;

#2.创建触发器[tri_user_index]在user表插入输入时生效。
CREATE TRIGGER tri_user_index BEFORE insert on user

#3.循环user表,查询user表的index输入,每次数据加1
for each row
BEGIN
set @new_index = 1;
select index into @new_index from user order by index desc limit 1;
set new.index=@new_index+1;
end

Guess you like

Origin blog.csdn.net/qq_37959253/article/details/127194324