您的位置:首页 > 产品设计 > UI/UE

MySQL实现序列(Sequence)效果

2016-07-22 11:32 459 查看
由于mysql不带sequence,所以要手写的,创建一张储存sequence的表(tb_sequence),然后手动插入一条数据 ,最后自定义一个函数来处理要增长的值。

1、创建表tb_sequence,用来存放sequence值:

create table tb_sequence(name varchar(50) not null,current_value int not null,_increment int not null default 1, primary key(name));


2、手动插入数据:

insert into tb_sequence values('userid',100,2);


3、定义函数 _nextval:

DELIMITER //
create function _nextval(n varchar(50)) returns integer
begin
declare _cur int;
set _cur=(select current_value from tb_sequence where name= n);
update tb_sequence
set current_value = _cur + _increment
where name=n ;
return _cur;
end;
//


说明:delimiter // —->定义语句结束符。其他的代码 自己看吧。

4、恢复默认的语句结束符:(可以省略但是结束符必须用// ,为了方便还是设置回来。)

DELIMITER ;


5、检验结果

多次执行以下语句:

select _nextval('userid');


结果显示:

mysql> select _nextval('userid');
+--------------------+
| _nextval('userid') |
+--------------------+
|                102 |
+--------------------+
1 row in set (0.00 sec)

mysql> select _nextval('userid');
+--------------------+
| _nextval('userid') |
+--------------------+
|                104 |
+--------------------+
1 row in set (0.00 sec)

mysql> select _nextval('userid');
+--------------------+
| _nextval('userid') |
+--------------------+
|                106 |
+--------------------+
1 row in set (0.00 sec)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql