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

前端 未结 4 574
忘了有多久
忘了有多久 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 06:03

    I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

    CREATE TABLE YOURTABLE(
    IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
    ENAME VARCHAR(30) not null
    );
    

    Perform a select and use this select query and save to the parameter @IDNUMBER

    (SELECT IFNULL
         (CONCAT('LHPL',LPAD(
           (SUBSTRING_INDEX
            (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
        AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)
    

    And then Insert query will be :

    INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
    (@IDNUMBER, 'EMPLOYEE NAME');
    

    The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

提交回复
热议问题