MySql非主鍵序列自增
阿新 • • 發佈:2021-02-04
MySql只能建立一個表字段的序列自增,如果需要兩個或者多個序列自增就需要如下方法:
此處設定了兩個序列自增供使用:
一: 建立一張表格:sequence 增加如下三個欄位 1.序列名稱 2.當前序列的值 3.步長:每次增加的數值
drop table if exists sequence;
create table sequence (
seq_name VARCHAR(50) NOT NULL, -- 序列名稱
current_val INT NOT NULL, -- 當前值
increment_val INT NOT NULL DEFAULT 1, -- 步長(跨度)
PRIMARY KEY (seq_name) );
二: 為表字段建立兩組資料
INSERT INTO sequence VALUES ('member', '0', '1');
INSERT INTO sequence VALUES ('sort_num', '0', '1');
三:建立 函式 用於獲取序列當前值(v_seq_name 引數值 代表序列名稱)
create function currval(v_seq_name VARCHAR (50))
returns integer
begin
declare value integer;
set value = 0;
select current_val into value from sequence where seq_name = v_seq_name;
return value;
end;
四:查詢當前序列的值
select currval('member');
select currval('sort_num');
五: 建立 函式 用於獲取序列下一個值(v_seq_name 引數值 代表序列名稱)
create function nextval (v_seq_name VARCHAR(50))
returns integer
begin
update sequence set current_val = current_val + increment_val where seq_name = v_seq_name;
return currval(v_seq_name);
end;
六: 查詢序列的下一個值
select nextval('member');
select nextval('sort_num');
七:展示建立的函式 以及 指定函式名刪除函式
show function STATUS
drop function currval
drop function nextval
八: 通過呼叫查詢資料庫,獲取序列值,然後操作
<select id="getMember" resultType="java.lang.Integer">
select nextval('member');
</select>
<select id="getSortNum" resultType="java.lang.Integer">
select nextval('sort_num');
</select>