mysql 实现序列

一 前言

1、oracle和mysql相比真的是一个天一个地,mysql没有序列,只有主键自增,如果需要自定义主键含义则需要实现序列。

2、思路很简单,创建函数 通过查询出当前值+步长跟新到原来的当前值,实现每一次查询都有自增后的值。

3、如果考虑并发脏数据,需要进行加锁控制(本文,为不解释连招,不详说)

二 实验

-- 创建序列专用表   序列名 初始值 步长1
create table mysql_seq (
	name varchar(50) not null primary key,
	start_value int not null,
	increment_value int not null default 1
);

-- 创建序列
insert into mysql_seq values('SEQ_TEST',1,1);


-- 定义获取序列函数
DELIMITER //
create  function nextval(str varchar(50)) returns integer
begin
	declare i int;
	set i=(select start_value from mysql_seq where name=str);
	update mysql_seq
		set start_value=i+increment_value
	where name=str;
return i;
end;
//


-- 使用序列
select nextval('SEQ_TEST');
select nextval('SEQ_TEST');
select nextval('SEQ_TEST');

三 验证

猜你喜欢

转载自blog.csdn.net/qq_22211217/article/details/81286784