mysql 自定義自增序列

2021-07-09 11:12:24 字數 1466 閱讀 7499

公司專案需求需要在一張包含自增主鍵的mysql表中,再次增加乙個自增字段,但是mysql只支援一張表乙個自增字段。

create table if not exists `sequence` (  

`name` varchar(50) not null,

`current_value` int(11) not null,

`increment` int(11) not null default '1'

) engine=myisam default charset=utf8 checksum=1 delay_key_write=1 row_format=dynamic comment='序列表,命名s_[table_name]';

插入一條資料

insert into `sequence` (`name`, `current_value`, `increment`) values  

('s_food_account', 0, 1) 

建立兩個mysql的自定義函式

drop function if exists `currval`;  

delimiter //

create function `currval`(seq_name varchar(50)) returns int(11)

reads sql data

deterministic

begin

declare value integer;

set value = 0;

select current_value into value from sequence where name = seq_name;

return value;

end//

delimiter ;

drop function if exists `nextval`;

delimiter //

create function `nextval`(seq_name varchar(50)) returns int(11)

deterministic

begin

update sequence set current_value = current_value + increment where name = seq_name;

return currval(seq_name);

end//

delimiter ;

select nextval("s_food_account") 的時候呼叫函式nextval 更新表sequence 按照步長自增一,步長也是可以自定義的,然後在條件查詢,兩個函式是可以寫成乙個的。

mysql實現自定義sequence自增序列

mysql資料庫沒有oracle資料庫中sequence序列,mysql中只有auto increment自增,這種自增方式只能是整數型別的,如果要自定義的自增序列,mysql就不能實現。這裡,提供mysql實現自定義sequence自增序列的一種方法。drop table if exists se...

自定義TextBox,實現自增自減

我們使用附加屬性來實現,依賴屬性也可以實現,原理一樣 如圖xmal cs,定義附加屬性 using system using system.collections.generic using system.linq using system.text using system.threading.t...

MySQL 自增序列

5.7.23 select version 非主鍵形式的自增欄位 create table test3 id int auto increment not null,str varchar 2 key id 自增預設從1開始 truncat後,自增序列重新開始 設定自增開始值 同時 建立自增序列字段...