怎么在mysql中实现sequence功能

33次阅读
没有评论

共计 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 问一下细节

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-04发表,共计1423字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)