Home > Database > Mysql Tutorial > How to Create an Auto-Incrementing Primary Key with a Prefix in MySQL?

How to Create an Auto-Incrementing Primary Key with a Prefix in MySQL?

DDD
Release: 2024-12-17 16:32:15
Original
964 people have browsed it

How to Create an Auto-Incrementing Primary Key with a Prefix in MySQL?

Auto-Incrementing Primary Key with Prefix in MySQL

In need of an auto-incrementing primary key with a specified prefix, such as 'LHPL001', 'LHPL002', and so on? Here's a concise guide to achieve this in MySQL.

One approach involves utilizing a separate sequencing table and a trigger to generate the desired prefix. Below are the steps:

  1. Create the sequencing table:

    CREATE TABLE table1_seq
    (
      id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
    );
    Copy after login
  2. Create the target table with a plain VARCHAR primary key:

    CREATE TABLE table1
    (
      id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0',
      name VARCHAR(30)
    );
    Copy after login
  3. Create the trigger:

    DELIMITER $$
    CREATE TRIGGER tg_table1_insert
    BEFORE INSERT ON table1
    FOR EACH ROW
    BEGIN
      INSERT INTO table1_seq VALUES (NULL);
      SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
    END$$
    DELIMITER ;
    Copy after login

With this setup, you can now insert rows into table1, and the trigger will automatically generate the prefixed primary key:

INSERT INTO Table1 (name) 
VALUES ('Jhon'), ('Mark');
Copy after login

The result in the table1 table will be:

|      ID | NAME |
------------------
| LHPL001 | Jhon |
| LHPL002 | Mark |
Copy after login

Refer to the provided SQLFiddle demo for an interactive demonstration of this approach.

The above is the detailed content of How to Create an Auto-Incrementing Primary Key with a Prefix in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template