更新时间:2022-02-11 22:37:54
问题并不像看起来那样容易.在BEFORE INSERT
触发器中,尚未生成自动增量值(NEW.autoinc_column
为0
),在AFTER INSERT
触发器中,无法再更改要插入的值.
The problem is not as easy as it seems. In a BEFORE INSERT
trigger, the autoincrement value hasn't been generated yet (NEW.autoinc_column
is 0
), and in an AFTER INSERT
trigger, it is not possible anymore to change the values to be inserted.
对于MyISAM表,您可以检查表定义中的下一个AUTO_INCREMENT
值:
With MyISAM tables, you could check the table definition for the next AUTO_INCREMENT
value:
DELIMITER //
CREATE TRIGGER inserName BEFORE INSERT ON name FOR EACH ROW
BEGIN
DECLARE next_ai INT;
SELECT auto_increment INTO next_ai
FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name = 'name';
SET NEW.name = CONCAT("I am number ", next_ai);
END //
DELIMITER ;
我相信,如果innodb_autoinc_lock_mode = 0
(默认情况下不是这种情况),这也适用于InnoDB表,但是我不确定(因为可能存在并发问题).
I believe this could work too with InnoDB tables if innodb_autoinc_lock_mode = 0
(not the case by default), but I am not sure (because of possible concurrency issues).
但是,如果concat的值始终相同,则***使用如下视图:
But if the value to concat is always the same, you probably had better using a view such as:
CREATE VIEW names_v AS SELECT id, CONCAT("I am number ", id) AS name FROM names;