mysql identity 與sequence的區別 與 mysql 實現 oracle sequence
Posted on 2013-07-19 21:39 云云 閱讀(2896) 評論(1) 編輯 收藏Sequence是數據庫系統的特性,有的數據庫有Sequence,有的沒有。比如Oracle、DB2、PostgreSQL數據庫有Sequence,MySQL、SQL Server、Sybase等數據庫沒有Sequence。
定義一個seq_test,最小值為10000,最大值為99999999999999999,從20000開始,增量的步長為1,緩存為20的循環排序Sequence。
Oracle的定義方法:
定義一個seq_test,最小值為10000,最大值為99999999999999999,從20000開始,增量的步長為1,緩存為20的循環排序Sequence。
Oracle的定義方法:
create sequence seq_test
minvalue 10000
maxvalue 99999999999999999
start with 20000
increment by 1
cache 20
cycle
order;
Sequence與indentity的基本作用都差不多。都可以生成自增數字序列。
Sequence是數據庫系統中的一個對象,可以在整個數據庫中使用,和表沒有任何關系;indentity僅僅是指定在表中某一列上,作用范圍就是這個表。
一個表中可以有多個字段使用sequence字段
insert into temp(event_id,event_priority,event_status) values(sequence1.nextval, sequence1.nextval,sequence1.nextval);
mysql 實現sequence
由于mysql不帶sequence,所以要手寫的,創建一張儲存sequence的表(tb_sequence),然后手動插入一條數據 ,最后自定義一個函數來處理要增長的值。
minvalue 10000
maxvalue 99999999999999999
start with 20000
increment by 1
cache 20
cycle
order;
Sequence與indentity的基本作用都差不多。都可以生成自增數字序列。
Sequence是數據庫系統中的一個對象,可以在整個數據庫中使用,和表沒有任何關系;indentity僅僅是指定在表中某一列上,作用范圍就是這個表。
一個表中可以有多個字段使用sequence字段
insert into temp(event_id,event_priority,event_status) values(sequence1.nextval, sequence1.nextval,sequence1.nextval);
mysql 實現sequence
由于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);
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;
select _nextval('userid');