且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用MySQL触发器插入新记录后更新表列

更新时间:2023-02-04 23:32:49

您尝试为列设置值的方法是更新.因为您正在插入操作完成之后执行此操作.

The way you are trying to set value to a column is an update. Because you are doing it after insert operation is completed.

您实际上需要一个before触发器.

You actually need a before trigger.

并为同一表的主键列分配相同的新自动递增值,***从information_schema.tables获取.

And to assign the same new auto incremented value of primary key column of same table, you better get it from information_schema.tables.

示例 :

Example:

delimiter //
drop trigger if exists bi_table_name //

create trigger bi_table_name before insert on table_name
for each row begin
  set @auto_id := ( SELECT AUTO_INCREMENT 
                    FROM INFORMATION_SCHEMA.TABLES
                    WHERE TABLE_NAME='table_name'
                      AND TABLE_SCHEMA=DATABASE() ); 
  set new.priority= @auto_id;
end;
//

delimiter ;

注意 : 确保您没有任何具有相同名称和/或动作的预定义触发器. 如果有的话,请先删除它们,然后再创建新的.

Note: Make sure that you don't have any pre-defined trigger with the same name and/or action. If have some, then drop them before creating the new.

观察:
根据上的 mysql文档last_insert_id()

Observations:
As per mysql documentation on last_insert_id(),

"如果您使用单个INSERT语句插入多行, LAST_INSERT_ID()返回为第一个插入生成的值 仅行."

"if you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only."

因此,

因此,取决于批量插入中的last_insert_id()auto_increment字段值似乎不可靠.

hence, depending on last_insert_id() and auto_increment field values in batch inserts seems not reliable.