mysql 自增長序列

2021-09-11 11:20:26 字數 2581 閱讀 5199

我們在什麼情況下可能使用序列呢

1.業務複雜,需要定製和控制主鍵時(自增主鍵只能按數字遞增的,但是序列可以隨心所欲的變化,比如我們按照年、月、日生成主鍵)

2.希望手工維護自增長,方便資料遷移

3.當事務跨多表,期望事務可靠性時

4.需要業務上有意義的主鍵時,比如流水號

5.主鍵很明確地需要和其他表關聯

6.期望主鍵是唯一,但不需要重複列用時

當然也有缺點,主要時程式處理麻煩。而且mysql只能通過觸發器模擬,會有一些效能損失。

比較自增主鍵和序列之間的異同以及優缺點,在mysql中使用自增主鍵更方便。但這裡仍然推薦使用序列,

因為其有更好的定製性和可控性。對於innodb,雖然序列的可定製性強,

但是如果使用序列,則不推薦使用char等和非number型資料坐主鍵,因為這樣會影響innodb的插入效能

drop table if exists sequence; 

create table sequence (

name varchar(30) not null,

current_value int not null,

increment int not null default 1,

primary key (name)

) engine=innodb;

drop function if exists currval; 

delimiter $

create function currval (seq_name varchar(30))

returns integer

language sql

deterministic

contains sql

sql security definer

comment ''

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 integer

language sql

deterministic

contains sql

sql security definer

comment ''

begin

update sequence

set current_value = current_value + increment

where name = seq_name;

return currval(seq_name);

end$

delimiter ;

drop function if exists setval; 

delimiter $

create function setval (seq_name varchar(50), value integer)

returns integer

language sql

deterministic

contains sql

sql security definer

comment ''

begin

update sequence

set current_value = value

where name = seq_name;

return currval(seq_name);

end$

delimiter ;

然後我們就需要進行去管理

insert into sequence values ('item_id', 0, 1);   #插入一條資料,新增乙個sequence名稱和初始值,以及自增幅度

select setval('item_id', 1); #設定指定sequence的初始值

select currval('item_id'); #查詢指定sequence的當前值

select nextval('item_id'); #查詢指定sequence的下乙個值

#使用自增

inset into user (id,username,email,password) values (nextval('item_id'),'張三','[email protected]','123')

oracle自增長序列

例1 建立序列 create sequence abc increment by1 start with 1maxvalue 9999999999 nocycle nocache 語法詳解 create sequence 序列名 increment by n 1 start with n 2 3 4...

自增長序列 serial

serial create table tuniq idserial,name text insert into tuniq name values zero insert into tuniq name values second 表名 欄位名 seq 實現的,每次插入的時候會從這個seq中取值作...

oracle中建立自增長序列

首先建立序列 create sequence incr stu id seq minvalue 1 start with 1 increment by 1 nomaxvalue nocache 然後建立觸發器 create or replace trigger incr stu id trig be...