zoukankan      html  css  js  c++  java
  • mysql 如何设置自动增长序列 sequence(一)

    背景:由于项目需要,必须用mysql设置主键自增长,而且想用字符串的。经过上网查找并且实验,终于做出了一套方案。现在就共享给大家!


    解决思路:由于mysql不带sequence,所以要手写的,创建一张储存sequence的表(tb_sequence),然后手动插入一条数据 ,最后自定义一个函数来处理要增长的值。

    一起做吧:

    1、创建表tb_sequence,用来存放sequence值:

    [sql] view plain copy
     
     print?
    1. create table tb_sequence(name varchar(50) not null,current_value int not null,_increment int not null default 1, primary key(name));   


    2、手动插入数据:

    [sql] view plain copy
     
     print?
    1. insert into tb_sequence values('userid',100,2);  


    3、定义函数 _nextval:

    [sql] view plain copy
     
     print?
    1. DELIMITER //  
    2. create function _nextval(n varchar(50)) returns integer   
    3. begin  
    4. declare _cur int;  
    5. set _cur=(select current_value from tb_sequence where name= n);  
    6. update tb_sequence  
    7.  set current_value = _cur + _increment  
    8.  where name=n ;  
    9. return _cur;  
    10. end;  
    11. //  


    说明:delimiter //   ---->定义语句结束符。其他的代码 自己看吧。

    4、恢复默认的语句结束符:(可以省略但是结束符必须用// ,为了方便还是设置回来。)

    [sql] view plain copy
     
     print?
    1. DELIMITER ;  


    5、检验结果 

    多次执行以下语句:

    [sql] view plain copy
     
     print?
    1. select _nextval('userid');  


    结果显示:

    [sql] view plain copy
     
     print?
    1. mysql> select _nextval('userid');  
    2. +--------------------+  
    3. | _nextval('userid') |  
    4. +--------------------+  
    5. |                102 |  
    6. +--------------------+  
    7. 1 row in set (0.00 sec)  
    8.   
    9. mysql> select _nextval('userid');  
    10. +--------------------+  
    11. | _nextval('userid') |  
    12. +--------------------+  
    13. |                104 |  
    14. +--------------------+  
    15. 1 row in set (0.00 sec)  
    16.   
    17. mysql> select _nextval('userid');  
    18. +--------------------+  
    19. | _nextval('userid') |  
    20. +--------------------+  
    21. |                106 |  
    22. +--------------------+  
    23. 1 row in set (0.00 sec)  


    6、实验结束。

     

  • 相关阅读:
    spring boot + swagger2
    itext7 html转pdf实现
    shell脚本学习
    观察者模式
    sql mode 问题及解决 错误代码:1055 this is incompatible with sql_mode=only_full_group_by
    学生报数算法实现
    git reset 版本回退操作
    struts2方法无法映射问题:There is no Action mapped for namespace [/] and action name [m_hi] associated with context path []
    Vue日历组件的功能
    vue-router 在新窗口打开页面的功能
  • 原文地址:https://www.cnblogs.com/husam/p/5333568.html
Copyright © 2011-2022 走看看