Mysql实现全局唯一ID

来源:互联网 发布:java技术 编辑:程序博客网 时间:2024/05/18 01:24

https://segmentfault.com/a/1190000004201384

因为MYSQL没有ORACLE中的sequence概念,所以需要建立一个表来模拟sequence,同时也可以作为高位数据保存。

CREATE TABLE IF NOT EXISTS `sys_sequence` (  `id` int(11) unsigned NOT NULL,  `no` varchar(4) NOT NULL DEFAULT '',  `name` varchar(64) NOT NULL DEFAULT '') ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;ALTER TABLE `sys_sequence` ADD PRIMARY KEY (`id`);
创建MYSQL函数:

create function `get_sequence`(`in_name` varchar(64)) returns varchar(16) charset utf8begin    declare p_last_id int;    declare p_no      varchar(4);    declare p_result  varchar(16);    declare p_max_no  int;    insert into sys_sequence () values ();    select last_insert_id() into p_last_id;    delete from sys_sequence where id = p_last_id;    if(in_name is not null and in_name <> '') then        select no into p_no from sys_sequence where name = in_name;        if(p_no is null) then            select max(cast(no as unsigned)) into p_max_no from sys_sequence;            set p_no = lpad(p_max_no + 1, 4, 0);            insert into sys_sequence (no, name) values (p_no, in_name);        end if;    else        set p_no = '0000';    end if;    set p_result = concat(p_no, lpad(p_last_id, 12, 0));    return p_result;end

参考资料

  • 数据库唯一ID的实现思路

  • 全局唯一ID生成方案对比

  • Ticket Servers: Distributed Unique Primary Keys on the Cheap