共計 1423 個字符,預計需要花費 4 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
這篇文章將為大家詳細講解有關怎么在 mysql 中實現 sequence 功能,文章內容質量較高,因此丸趣 TV 小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
mysql 實現 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 基礎函數
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `_nextval`(name varchar(50)) RETURNS int(11)
begin
declare _cur int;
declare _maxvalue int; -- 接收最大值
declare _increment int; -- 接收增長步數
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 -- 更新當前值
set current_value = _cur + increment_value
where seq_name = name ;
if(_cur + _increment = _maxvalue) then -- 判斷是都達到最大值
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
關于怎么在 mysql 中實現 sequence 功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
向 AI 問一下細節
正文完