且构网

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

将一种自动增量列添加到mysql表中

更新时间:2023-12-01 09:09:04

MySQL不会自动增加除整数以外的任何内容.您不能自动增加字符串.

MySQL doesn't auto-increment anything other than integers. You can't auto-increment a string.

您不能使用触发器基于自动增量值来填充字符串.原因是在执行之前"触发器时尚未生成自动增量值,现在更改之后"触发器中的列为时已晚.

You can't use a trigger to populate a string based on the auto-increment value. The reason is that the auto-increment value isn't generated yet at the time "before" triggers execute, and it's too late to change columns in "after" triggers.

另请参阅对 https://***.com/a/26899091/20860

出于相同的原因,您不能使用虚拟列.

You can't use a virtual column, probably for the same reason.

mysql> create table t (id int(5) zerofill auto_increment primary key, 
    virtcolumn char(8) as (concat('log-', id)));
ERROR 3109 (HY000): Generated column 'virtcolumn' cannot refer to auto-increment column.

您必须让整数自动递增,然后在插入完成后随后使用UPDATE填充"log-nnnnnn"字符串.

You'll have to let the integer auto-increment, and then subsequently use UPDATE to populate your "log-nnnnnn" string after the insert is done.

CREATE TABLE `t` (
  `id` int(5) unsigned zerofill NOT NULL AUTO_INCREMENT,
  `log` char(9) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `t` () VALUES ();

UPDATE `t` SET `log` = CONCAT('log-', `id`) WHERE `id` = LAST_INSERT_ID();

SELECT * FROM `t`;
+-------+-----------+
| id    | log       |
+-------+-----------+
| 00001 | log-00001 |
+-------+-----------+