mysql实现序列,用于表数据唯一固定主键

一、业务背景

1、oracle有自增序列,mysql有auto_increment,但是后者是在插入数据时实现自增,数据每增加一行,就加1
2、需求:同一个产品\指标,同一个id,且同一个产品\指标的id一旦生成,就固定不变

二、代码

-- 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');

三、效果

在这里插入图片描述

四、参考资料

MYSQL 序列使用及实现

猜你喜欢

转载自blog.csdn.net/shammy_feng/article/details/121351553