1. 사업 배경
1. Oracle은 auto-increment sequence가 있고 mysql은 auto_increment가 있지만 후자는 데이터를 삽입할 때 auto-increment를 구현합니다. 데이터의 추가 행마다 1이 추가됩니다
. 2. 요구 사항: 동일한 product\indicator, 동일한 id , 그리고 동일한 제품 \Indicator의 id는 생성되면 고정됩니다.
2. 코드
-- 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');