我是靠谱客的博主 小巧大山,这篇文章主要介绍MySQL中使用序列Sequence的方式总结,现在分享给大家,希望可以做个参考。

推荐学习:mysql视频教程

在Oracle数据库中若想要一个连续的自增的数据类型的值,可以通过创建一个sequence来实现。而在MySQL数据库中并没有sequence。通常如果一个表只需要一个自增的列,那么我们可以使用MySQL的auto_increment(一个表只能有一个自增主键)。若想要在MySQL像Oracle中那样使用序列,我们该如何操作呢?

例如存在如下表定义:

复制代码
1
2
3
4
5
create table `t_user`( `id` bigint auto_increment primary key, `user_id` bigint unique comment '用户ID', `user_name` varchar(10) not null default '' comment '用户名' );
登录后复制

其中user_id要求自增有序且唯一。实现方式有很多比如雪花算法、使用Redis或者Zookeeper等都可以获取一个满足条件的值,这里就不一一介绍。这里介绍使用MySQL的auto_increment和last_insert_id()来实现类似Oracle中的序列的方式。

方式一、使用存储过程

一、创建一个包含自增主键的简单表。

示例如下:

复制代码
1
2
3
4
create table `t_user_id_sequence` ( `id` bigint not null auto_increment primary key, `t_text` varchar(5) not null default '' comment 'insert value' );
登录后复制

二、创建一个存储过程

复制代码
1
2
3
4
5
6
7
8
delimiter && create procedure `pro_user_id_seq` (out sequence bigint) begin insert into t_user_id_sequence (t_text) values ('a'); select last_insert_id() into sequence from dual; delete from t_user_id_sequence; end && delimiter ;
登录后复制

三、测试

复制代码
1
2
call pro_user_id_seq(@value); select @value from dual;
登录后复制

使用存储过程的方式需要调用一次存储过程再进行赋值,稍微有点麻烦。

方式二、使用function

一、创建一个生成sequence的函数

复制代码
1
2
3
4
5
6
7
8
9
10
delimiter && create function user_id_seq_func() returns bigint begin declare sequence bigint; insert into t_user_id_sequence (t_text) values ('a'); select last_insert_id() into sequence from dual; delete from t_user_id_sequence; return sequence; end && delimiter ;
登录后复制

二、测试

复制代码
1
2
3
4
select user_id_seq_func() from dual; insert into t_user (user_id, user_name) values (user_id_seq_func(), 'java'); select * from t_user;
登录后复制

推荐学习:mysql视频教程

以上就是MySQL中使用序列Sequence的方式总结的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是小巧大山最近收集整理的关于MySQL中使用序列Sequence的方式总结的全部内容,更多相关MySQL中使用序列Sequence内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(107)

评论列表共有 0 条评论

立即
投稿
返回
顶部