一、业务背景
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');