MySQL中使用序列Sequence的方式總結
前言
在Oracle數(shù)據(jù)庫中若想要一個連續(xù)的自增的數(shù)據(jù)類型的值,可以通過創(chuàng)建一個sequence來實現(xiàn)。而在MySQL數(shù)據(jù)庫中并沒有sequence。通常如果一個表只需要一個自增的列,那么我們可以使用MySQL的auto_increment(一個表只能有一個自增主鍵)。若想要在MySQL像Oracle中那樣使用序列,我們該如何操作呢?
例如存在如下表定義:
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要求自增有序且唯一。實現(xiàn)方式有很多比如雪花算法、使用Redis或者Zookeeper等都可以獲取一個滿足條件的值,這里就不一一介紹。這里介紹使用MySQL的auto_increment和last_insert_id()來實現(xiàn)類似Oracle中的序列的方式。
方式一、使用存儲過程
一、創(chuàng)建一個包含自增主鍵的簡單表。
示例如下:
create table `t_user_id_sequence` ( `id` bigint not null auto_increment primary key, `t_text` varchar(5) not null default '' comment 'insert value' );
二、創(chuàng)建一個存儲過程
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 ;
三、測試
call pro_user_id_seq(@value); select @value from dual;
使用存儲過程的方式需要調(diào)用一次存儲過程再進行賦值,稍微有點麻煩。
方式二、使用function
一、創(chuàng)建一個生成sequence的函數(shù)
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 ;
二、測試
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中使用序列Sequence方式的文章就介紹到這了,更多相關MySQL使用序列Sequence內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一步步教你如何使用mysql?binlog恢復數(shù)據(jù)
Binlog日志即binary?log,是二進制日志文件,有兩個作用,一個是增量備份,另一個是主從復制,下面這篇文章主要給大家介紹了關于如何使用mysql?binlog?恢復數(shù)據(jù)的相關資料,需要的朋友可以參考下2023-04-04MySQL?從0到1打開數(shù)據(jù)庫管理操作方法
數(shù)據(jù)庫管理系統(tǒng)(DataBase?Management?System)是用來創(chuàng)建數(shù)據(jù)庫和管理數(shù)據(jù)庫數(shù)據(jù)的一個管理軟件,我們口頭說的MySQL數(shù)據(jù)庫就是這個管理系統(tǒng),這篇文章主要介紹了MySQL從0到1打開數(shù)據(jù)庫管理,需要的朋友可以參考下2023-06-06