MySQL中使用序列Sequence的方式總結(jié)
前言
在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)用一次存儲過程再進(jìn)行賦值,稍微有點麻煩。
方式二、使用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;
總結(jié)
到此這篇關(guān)于MySQL中使用序列Sequence方式的文章就介紹到這了,更多相關(guān)MySQL使用序列Sequence內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mysql修改datadir導(dǎo)致無法啟動問題解決方法
這篇文章主要介紹了Mysql修改datadir導(dǎo)致無法啟動問題解決方法,本文原因是SELINUX導(dǎo)致,用關(guān)閉SELINUX的方法解決了這個問題,需要的朋友可以參考下2015-02-02
MySQL 5.7增強版Semisync Replication性能優(yōu)化
這篇文章主要介紹了MySQL 5.7增強版Semisync Replication性能優(yōu)化,本文著重講解支持發(fā)送binlog和接受ack的異步化、支持在事務(wù)commit前等待ACK兩項內(nèi)容,需要的朋友可以參考下2015-05-05
mysql執(zhí)行腳本導(dǎo)入表和數(shù)據(jù)后中文注釋亂碼的問題解決
本人在使用不同版本下進(jìn)行操作時,就會出現(xiàn)中文亂碼的問題,,例如我本地安裝mysql8,服務(wù)器安裝的是mysql5,然后本地連接服務(wù)器的mysql后,執(zhí)行SQL腳本之后發(fā)現(xiàn)中文全部亂碼,所以本文介紹了mysql執(zhí)行腳本導(dǎo)入表和數(shù)據(jù)后中文注釋亂碼的問題解決,需要的朋友可以參考下2024-04-04
MYSQL數(shù)據(jù)庫表結(jié)構(gòu)優(yōu)化方法詳解
這篇文章主要介紹了MYSQL數(shù)據(jù)庫表結(jié)構(gòu)優(yōu)化方法,總結(jié)分析了mysql針對表結(jié)構(gòu)優(yōu)化的數(shù)據(jù)類型選擇、范式化操作、表的拆分等相關(guān)使用技巧,需要的朋友可以參考下2019-08-08

