我的Java路上那些事兒

          快樂(lè)成長(zhǎng)
          posts - 110, comments - 101, trackbacks - 0, articles - 7
            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理
          Sequence是數(shù)據(jù)庫(kù)系統(tǒng)的特性,有的數(shù)據(jù)庫(kù)有Sequence,有的沒(méi)有。比如Oracle、DB2、PostgreSQL數(shù)據(jù)庫(kù)有Sequence,MySQL、SQL Server、Sybase等數(shù)據(jù)庫(kù)沒(méi)有Sequence。
          定義一個(gè)seq_test,最小值為10000,最大值為99999999999999999,從20000開(kāi)始,增量的步長(zhǎng)為1,緩存為20的循環(huán)排序Sequence。
          Oracle的定義方法:
          create sequence seq_test
          minvalue 10000
          maxvalue 99999999999999999
          start with 20000
          increment by 1
          cache 20
          cycle
          order;
          Sequence與indentity的基本作用都差不多。都可以生成自增數(shù)字序列。
          Sequence是數(shù)據(jù)庫(kù)系統(tǒng)中的一個(gè)對(duì)象,可以在整個(gè)數(shù)據(jù)庫(kù)中使用,和表沒(méi)有任何關(guān)系;indentity僅僅是指定在表中某一列上,作用范圍就是這個(gè)表。

          一個(gè)表中可以有多個(gè)字段使用sequence字段
          insert into temp(event_id,event_priority,event_status) values(sequence1.nextval, sequence1.nextval,sequence1.nextval);

          mysql 實(shí)現(xiàn)sequence

          由于mysql不帶sequence,所以要手寫(xiě)的,創(chuàng)建一張儲(chǔ)存sequence的表(tb_sequence),然后手動(dòng)插入一條數(shù)據(jù) ,最后自定義一個(gè)函數(shù)來(lái)處理要增長(zhǎng)的值。

          1、創(chuàng)建表tb_sequence,用來(lái)存放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 手動(dòng)插入數(shù)據(jù): 
            insert into tb_sequence values('userid',100,2);  
          3、定義函數(shù) _nextval:
          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;  
          檢驗(yàn)結(jié)果

           

          select _nextval('userid');  




          評(píng)論

          # re: mysql identity 與sequence的區(qū)別 與 mysql 實(shí)現(xiàn) oracle sequence   回復(fù)  更多評(píng)論   

          2014-06-12 11:15 by jie8476343
          在實(shí)際中發(fā)現(xiàn)高并發(fā)下會(huì)出現(xiàn)返回相同的值,請(qǐng)問(wèn)如何確保第一個(gè)線程執(zhí)行完_nextval,下一個(gè)線程才可以執(zhí)行

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 贡嘎县| 绵阳市| 双峰县| 尚志市| 金乡县| 武鸣县| 正镶白旗| 临朐县| 金阳县| 成安县| 寿光市| 邹平县| 盐边县| 关岭| 收藏| 花莲县| 平利县| 伊吾县| 岚皋县| 禹州市| 高青县| 忻州市| 开鲁县| 格尔木市| 吴旗县| 齐齐哈尔市| 昌乐县| 祥云县| 赣榆县| 邮箱| 武城县| 古浪县| 南京市| 榆中县| 页游| 汽车| 孙吴县| 微博| 吉木乃县| 城市| 湟中县|