背景
数据库常常使用自增主键。通常会遇到这些问题:当我们在导入旧数据时常常会发生主键重复冲突;数据库主键没有任何业务意义;常常会出现插入数据前需要获取数据主键的情况,MySQL下让人头大。
解决方案
生产过程中,常常用一张表以及函数来帮助维护业务表的主键。表用来存放业务表序列,函数用来处理并获取业务表序列。当有业务数据插入时,先通过函数获取该表的序列,此时可以通过此序列加上一些业务元素,即生成了有业务意义且唯一的主键。
序列表的创建
表主要两个字段,表名和当前序列号
CREATE TABLE `t_ads_sequence` (
`seq_name` varchar(50) NOT NULL,
`current_val` int(11) NOT NULL,
PRIMARY KEY (`seq_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='序列统计表';
序列函数的创建
函数一:用来获取当前序列
begin
declare value integer;
set value = 0;
select current_val into value from t_ads_sequence where seq_name = seq_nm;
return value;
end
函数二:用来获取下一个序列,并判断是否达到阀值,是就重置为0
begin
declare value int;
set value = currval(seq_nm);
if value<999999999 then
update t_ads_sequence set current_val = current_val + 1 where seq_name = seq_nm;
else
update t_ads_sequence set current_val = 0 where seq_name = seq_nm;
end if;
RETURN currval(seq_nm);
end
使用例子
SELECT nextVal('base_info');