Mysql实现全局唯一ID

838 查看

因为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 utf8
begin
    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

参考资料