mysql實(shí)現(xiàn)sequence功能的代碼
mysql實(shí)現(xiàn)sequence功能
1.建立sequence記錄表
CREATE TABLE `sys_sequence` ( `seq_name` varchar(50) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL, `min_value` int(11) NOT NULL, `max_value` int(11) NOT NULL, `current_value` int(11) NOT NULL, `increment_value` int(11) NOT NULL DEFAULT '1', PRIMARY KEY (`seq_name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
2.建立sequence基礎(chǔ)函數(shù)
DELIMITER $$ CREATE DEFINER=`root`@`%` FUNCTION `_nextval`(name varchar(50)) RETURNS int(11) begin declare _cur int; declare _maxvalue int; -- 接收最大值 declare _increment int; -- 接收增長(zhǎng)步數(shù) set _increment = (select increment_value from sys_sequence where seq_name = name); set _maxvalue = (select max_value from sys_sequence where seq_name = name); set _cur = (select current_value from sys_sequence where seq_name = name); update sys_sequence -- 更新當(dāng)前值 set current_value = _cur + increment_value where seq_name = name ; if(_cur + _increment >= _maxvalue) then -- 判斷是都達(dá)到最大值 update sys_sequence set current_value = min_value where seq_name = name ; end if; return _cur; end$$ DELIMITER ;
3.插入想要建立的sequence
INSERT INTO `mydb`.`sys_sequence` (`seq_name`, `min_value`, `max_value`, `current_value`, `increment_value`) VALUES ('seq_name1', 1, 99999999, 1, 1);
4.使用sequence
select _nextval('seq_name1');
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
如何將mysql存儲(chǔ)位置遷移到一塊新的磁盤(pán)上
這篇文章主要介紹了如何將mysql存儲(chǔ)位置遷移到一塊新的磁盤(pán)上,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12MySQL數(shù)據(jù)庫(kù)備份恢復(fù)實(shí)現(xiàn)代碼
這篇文章主要介紹了MySQL數(shù)據(jù)庫(kù)備份恢復(fù)實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06mysql遠(yuǎn)程登錄root賬戶報(bào)錯(cuò)1045的解決
這篇文章主要介紹了mysql遠(yuǎn)程登錄root賬戶報(bào)錯(cuò)1045的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04深入mysql外鍵關(guān)聯(lián)問(wèn)題的詳解
本篇文章是對(duì)mysql外鍵關(guān)聯(lián)問(wèn)題進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06深入解析MySQL索引數(shù)據(jù)結(jié)構(gòu)
什么是索引?索引就是排好序的數(shù)據(jù)結(jié)構(gòu),可以幫助我們快速的查找到數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于MySQL索引數(shù)據(jù)結(jié)構(gòu)的相關(guān)資料,需要的朋友可以參考下2021-10-10