背景:由於項目需要,必須用mysql設置主鍵自增長,而且想用字符串的。經過上網查找並且實驗,終於做出了一套方案。現在就共享給大家!
解決思路:由於mysql不帶sequence,所以要手寫的,創建一張儲存sequence的表(tb_sequence),然后手動插入一條數據 ,最后自定義一個函數來處理要增長的值。
一起做吧:
1、創建表tb_sequence,用來存放sequence值:
- create table tb_sequence(name varchar(50) not null,current_value int not null,_increment int not null default 1, primary key(name));
2、手動插入數據:
- insert into tb_sequence values('userid',100,2);
3、定義函數 _nextval:
- DELIMITER //
- create function _nextval(n varchar(50)) returns integer
- begin
- declare _cur int;
- set _cur=(select current_value from tb_sequence where name= n);
- update tb_sequence
- set current_value = _cur + _increment
- where name=n ;
- return _cur;
- end;
- //
說明:delimiter // ---->定義語句結束符。其他的代碼 自己看吧。
4、恢復默認的語句結束符:(可以省略但是結束符必須用// ,為了方便還是設置回來。)
- DELIMITER ;
5、檢驗結果
多次執行以下語句:
- select _nextval('userid');
結果顯示:
- mysql> select _nextval('userid');
- +--------------------+
- | _nextval('userid') |
- +--------------------+
- | 102 |
- +--------------------+
- 1 row in set (0.00 sec)
- mysql> select _nextval('userid');
- +--------------------+
- | _nextval('userid') |
- +--------------------+
- | 104 |
- +--------------------+
- 1 row in set (0.00 sec)
- mysql> select _nextval('userid');
- +--------------------+
- | _nextval('userid') |
- +--------------------+
- | 106 |
- +--------------------+
- 1 row in set (0.00 sec)
6、實驗結束。