husam

背景:由于项目需要,必须用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、实验结束。

 

 

分类:

技术点:

相关文章:

  • 2021-09-09
  • 2021-06-20
  • 2021-06-06
  • 2021-10-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
猜你喜欢
  • 2021-10-02
  • 2021-12-06
  • 2021-11-17
  • 2021-04-16
  • 2022-12-23
  • 2021-06-01
相关资源
相似解决方案