mysql_seq

介绍


mysq 中默认没有类似 oracle 的sequence 功能,我们自己写函数实现类似功能。
大致思路:

首先,建立一个存放seq的表,字段包括:当前值,自增值。
然后,定义nextval,currval函数,分别实现获取下次增长值和当前值。

实现


结构图:

avatar

建立seq的表
1
2
3
4
5
6
7
8
9
10
11
12
13
drop table if exists cm_sequence;
/*==============================================================*/
/* Table: cm_sequence */
/*==============================================================*/
create table cm_sequence
(
name varchar(50) not null comment '序列的名字,唯一',
current_value bigint not null comment '当前的值',
increment_value int not null default 1 comment '步长,默认为1',
primary key (name)
);

alter table cm_sequence comment '公共的序列表,用于为非自增且要求唯一的字段记录和获取唯一ID。
func_currval:获取当前序列的值并返回
1
2
3
4
5
6
7
8
9
10
11
12
drop function if exists func_currval;

create function func_currval (seq_name varchar(50))
RETURNS integer
begin
declare value integer;
set value = 0;
select current_value into value
from cm_sequence
where name = seq_name;
return value;
end;
func_nextval:获取序列中的一个可用的值
1
2
3
4
5
6
7
8
9
10
11
drop function if exists func_nextval;

create function func_nextval (seq_name varchar(50))
RETURNS integer
contains sql
begin
update cm_sequence
set current_value = current_value + increment_value
where name = seq_name;
return func_currval(seq_name);
end;
seq初始化、调用
1
2
insert into cm_sequence values('seq_cs',0,1);
select func_nextval('seq_cs') ;
seq并发测试
1
2
3
4
lock tables cm_sequence write 
select func_nextval('seq_cs')
select func_nextval('seq_cs')
unlock table