oracle的序列化和索引查找

来源:互联网 发布:网约车软件排行 编辑:程序博客网 时间:2024/06/08 07:26

在上面提到了,在oracle中我们并不能像在mysql 那样 给它一个自增长的主键 ,在oracle中要么用序列化来生成主键ID 要么就用varchar2l类型的,采用UUID来生成.

另外一个就是在涉及到大数据量的查询时候如果用 select * from 表, where ...,做全表查询找到数据的效率是很低的.在实际项目中我们是不予许这样的耗时操作的,所以在查询时候我们要为表的字段创建一个索引列;

-- oracle的序列化 一组有序有规则的数字,常常用来做为表的id(oracle中主键没有自增长)


  --sequence语法 create sequence 序列名称 
    start with n  从n开始
    increment by i 每次增长i,相当于步长
    minvalue  最小值
    maxvalue 最大值
    cycle/ nocycle 循环/不循环
    cache 10,意思是游标跳到当前步时候,往后缓存10步.
    currval 当前的值 (游标最开始默认的位置是-1,所以在使用前调用一次nextval)
    nextval 下一个值.
    
    create sequence mysequence 
    start with 1 increment by 2 minvalue 1 maxvalue 9 cache 5 cycle;
    select mysequence.nextval from dual;
    select mysequence.currval from dual; -- 1,3,5,7,9
   
   --实际开发中我们都是写下面的,给的是默认值, 
    create sequence se2;
    create table tb (
     se2NUM varchar2(20),
     NUM varchar2(20)
    );
    -- 我们先利用这个序列来往一个表中插入大量数据,为后面的索引查找做准备
    declare
    begin
      for i in 0..5000000 loop
        insert into tb values('tb'||se2.nextval,'tb'||i);
     end loop;
        commit;
      end;
      
      
     -- 索引
      
    --查询这500万条数据中的某一条,我们就要用索引  --- create index on 表名 (列名)
      1,--单列索引的使用
    select * from tb where tb.num = 'tb'||250000;--这是不用索引(我的电脑用了,26,458毫秒)
    create index index1 on tb (num);
    select * from tb where tb.num ='tb'||250000;--(0.089毫秒,这查询效率)
    -----------------------------------------------------------------------------------
    2,多列索引的使用,效率更高
    select * from tb where tb.se2num='tb'||400000 and tb.num='tb'||400000;--未使用多列索引(5,872)
    
    create index index2 on tb(se2num,num);
     select * from tb where tb.se2num='tb||400000' and tb.num='tb||400000';--创建了双列索引后查找的()