MySQL implements sequence for unique fixed primary key of table data

1. Business Background

1. Oracle has an auto-increment sequence, and mysql has auto_increment, but the latter realizes auto-increment when inserting data. For each additional row of data, 1 is added
. 2. Requirements: the same product\indicator, the same id, and the same product \The id of the indicator is fixed once it is generated

2. Code

-- 1、创建表sequence:
DROP TABLE
    IF EXISTS sequence;
CREATE TABLE
    sequence
    (
        name VARCHAR(50) NOT NULL,
        current_value BIGINT NOT NULL,
        increment INT NOT NULL DEFAULT 1,
        PRIMARY KEY (name)
    )
    ENGINE=InnoDB;
    
-- 2、插入定义的序列seq_index_code_no:
INSERT INTO sequence VALUES ('seq_index_code_no',0,1); -- 从0开始,每次加1

-- 3、创建函数seq实现自增:
delimiter &&
CREATE FUNCTION seq(seq_index_code_no char (20)) returns BIGINT
BEGIN
 UPDATE sequence SET current_value=last_insert_id(current_value+increment) WHERE name=seq_index_code_no;
 RETURN LAST_INSERT_ID();
END;

-- 4、验证和使用:
SELECT seq('seq_index_code_no');

3. Effect

insert image description here

4. References

MYSQL sequence usage and implementation

Guess you like

Origin blog.csdn.net/shammy_feng/article/details/121351553