How to make MySQL table primary key auto increment with some prefix

前端 未结 4 583
忘了有多久
忘了有多久 2020-11-22 05:38

I have table like this

table
id Varchar(45) NOT NULL AUTO_INCREMENT PRIMARY KEY,
name CHAR(30) NOT NULL,

I want to increment my id field li

4条回答
  •  天命终不由人
    2020-11-22 05:56

    Create a table with a normal numeric auto_increment ID, but either define it with ZEROFILL, or use LPAD to add zeroes when selecting. Then CONCAT the values to get your intended behavior. Example #1:

    create table so (
     id int(3) unsigned zerofill not null auto_increment primary key,
     name varchar(30) not null
    );
    
    insert into so set name = 'John';
    insert into so set name = 'Mark';
    
    select concat('LHPL', id) as id, name from so;
    +---------+------+
    | id      | name |
    +---------+------+
    | LHPL001 | John |
    | LHPL002 | Mark |
    +---------+------+
    

    Example #2:

    create table so (
     id int unsigned not null auto_increment primary key,
     name varchar(30) not null
    );
    
    insert into so set name = 'John';
    insert into so set name = 'Mark';
    
    select concat('LHPL', LPAD(id, 3, 0)) as id, name from so;
    +---------+------+
    | id      | name |
    +---------+------+
    | LHPL001 | John |
    | LHPL002 | Mark |
    +---------+------+
    

提交回复
热议问题