Mysql varchar型自增方法

来源:互联网 发布:python 遍历数组 编辑:程序博客网 时间:2024/06/05 12:06

为了测试,表中仅添加了两列,分别是主键id 和 name列,两列都为varchar类型。
备注:id内容格式为 BHXXXX,如:BH0001


因为主键id不是int类型,想实现自动自增功能,使用内置的方法肯定是行不通的,所以,使用了复杂的查询方法及拼接方式,
此方法虽然比较笨,但测试还是可以通过的。


大致思路:在MySql中新建表时,可以创建触发器为id进行自增。


详细思路:

    1、使用查询语句查出表中最后一条数据的id,语句:select id from user order by id desc limit 1     得到结果 BH0001


    2、使用substring函数截取最后一条BHXXXX中数字部分:

          SELECT substring(id,3,4) from user where id=(select id from user order by id desc limit 1)   得到结果 0001

           其中,3表示从第3位进行截取,4表示截取长度


   3、使用concat语句进行字符串连接

          concat('BH',(SELECT substring(id,3,4) from user where id=(select id from user order by id desc limit 1) +1));

          我刚开始认为到这一步的时候,只要给以上结果 +1 ,然后使用concat语句连接字符串就可以了,但是,得到的结果

          并不是我想象中的 BH0002,而是BH2,所以,在进行字符串连接之前,得将数字2进行填充,使用LPAD函数,最终结果如下:

          concat('BH',lpad(((SELECT substring(id,3,4) from user where id=(select id from user order by id desc limit 1))+1),4,0));

          其中,4表示填充长度,0表示填充内容。


触发器完整语句:

CREATE TRIGGER `T` BEFORE INSERT ON `user`
FOR EACH ROW begin
set new.id=concat('SH',lpad(((SELECT substring(id,3,4) from user where id=(select id from user order by id desc limit 1))+1),4,0));
end;

其中,大写T为触发器名称,user为表名,结束!


此解决方式可能有点笨,欢迎大家指点!


文章虽有原创一说,知识不涉及专利,我们应该用来分享,欢迎转载!

0 0