adding a kind of auto increment column to a mysql table

谁都会走 提交于 2021-02-05 06:00:07

问题


I want to add a column to a mysql table where its cells will get values like:

 newColumn
 -----------
 log-00001
 log-00002
 log-00003
 ....

the values log-0000x will automatically be created by mysql. This is like an "auto incremented" column but with the 'log-' prefix. Is this possible? Thx


回答1:


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.

See also my answer to https://stackoverflow.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.

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 |
+-------+-----------+


来源:https://stackoverflow.com/questions/44812494/adding-a-kind-of-auto-increment-column-to-a-mysql-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!