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、实验结束。

     

  • 相关阅读:
    02/Oct/2019:11:55:28 类型的时间转换为
    Flume 实时获取日志内容插入MySQL
    MySQL UTC时间转北京时间 | convert_tz()函数
    使用kettle实现循环
    python 获取系统环境变量 os.environ and os.putenv
    Python
    linux如何判断上一条命令执行是否正确
    局域网两台主机通过网络共享文件
    Kettle(Pentaho)实现web方式远程执行job或transformation
    kettle发送邮件 运行日志
  • 原文地址:https://www.cnblogs.com/husam/p/5333568.html
Copyright © 2011-2022 走看看