zoukankan      html  css  js  c++  java
  • oracle系列学习----复杂查询的优化

    实验数据和表

    create  table  test1
    (
        FID  NUMBER(6) NOT NULL,
        FBillNo VARCHAR2(10),
        FDate  DATE  DEFAULT to_date(to_char(SYSDATE,'yyyy-mm-dd'),'yyyy-mm-dd')
    )
    create sequence seq_test1
           minvalue 1  --最小值
           nomaxvalue --最大值
           start with 1 --起始值
           increment by 1  --增长基数
           nocycle  --不循环,一直增加
           nocache ;
    
    create trigger tri_test1_ins 
           before insert on test1 for each row  when (new.FID is null)
        begin 
          select seq_test1.nextval into:new.FID from dual;
        end;
        
        insert  into  test1(FBillNo ,  FDate)  values ('FB001' ,to_date('2018-6-1','yyyy-mm-dd'));
    insert  into  test1(FBillNo ,  FDate)  values ('FB002' ,  to_date('2018-6-3','yyyy-mm-dd'));
    insert  into  test1(FBillNo ,  FDate)  values ('FB003' ,  to_date('2018-2-1','yyyy-mm-dd'));
    insert  into  test1(FBillNo ,  FDate)  values ('FB003' ,  to_date('2018-2-3','yyyy-mm-dd'));
    
    DROP TABLE test2
    create  table  test4
    (
        FID  NUMBER(6),
        FBillNo  VARCHAR2(10),
        FDate  DATE DEFAULT to_date(to_char(SYSDATE,'yyyy-mm-dd'),'yyyy-mm-dd')
    )
    create sequence seq_test4
           minvalue 1  --最小值
           nomaxvalue --最大值
           start with 1 --起始值
           increment by 1  --增长基数
           nocycle  --不循环,一直增加
           nocache ;
    
    create trigger tri_test4_ins 
           before insert on test1 for each row  when (new.FID is null)
        begin 
          select seq_test4.nextval into:new.FID from dual;
        end;
        
        insert  into  test4(FBillNo ,  FDate)  values ('FB2018001' ,  to_date('2018-6-1','yyyy-mm-dd'));
      insert  into  test4(FBillNo ,  FDate)  values ('FB2018002' ,  to_date('2018-6-3','yyyy-mm-dd'));
      insert  into  test4(FBillNo ,  FDate)  values ('FB003' ,  to_date('2018-2-1','yyyy-mm-dd'));
      insert  into  test4(FBillNo ,  FDate)  values ('FB004' ,  to_date('2018-2-3','yyyy-mm-dd'));
    
    update  test1  set  FBillNo='FB004'  where  FDate=to_date('2018-2-3','yyyy-mm-dd')
    
    
    update  test1 t1 set  t1.FBillNo=(SELECT t2.FBillNo
    FROM  t1
    left  join  test4  t2  on  FID=t2.FID 
    where  t2.FDate>=to_date('2018-6-1','yyyy-mm-dd'))
    
    SELECT * FROM
    test1
    
    truncate  table  test4
    SELECT * FROM
    test4
    select  sex  as  性别 ,  count(*)  as 人数
    from  student
    group  by  sex
    select  *
    from
    (
        select  t2.name  as  姓名 ,  count(*)  as  不及格数
        from  exam  t1
        left  join  student  t2  on  t1.StudentID=t2.id
        where  t1.score<60
        group  by  t2.name
    )  t 
    select  t2.name  as  姓名 ,  count(*)  as 不及格数
    from  exam  t1
    left  join  student  t2  on  t1.StudentID=t2.id
    where  t1.score<60
    group  by  t2.name  having  count(*)>=1
    
    
    create  table  cust
    (
        numbers  VARCHAR2(10),
        city  VARCHAR2(10)
    )
    
    create table  ORDER_test
    (
        id NUMBER(6),
        custno varchar(100)
    )
    INSERT  INTO cust(numbers ,  city)  VALUES('163' ,  '杭州');
    INSERT  INTO cust(numbers ,  city)  VALUES('九游' ,  '上海');
    INSERT  INTO cust(numbers ,  city)  VALUES('腾迅' ,   '杭州');
    INSERT  INTO cust(numbers ,  city)  VALUES('百度' ,   '杭州');
    INSERT  INTO  order_test (id ,  custno)  VALUES(1 ,  '163');
    INSERT  INTO  order_test ( id ,  custno)  VALUES(2 ,  '163');
    INSERT  INTO  order_test ( id ,  custno)  VALUES(3 ,  '九游');
    INSERT  INTO  order_test ( id ,  custno)  VALUES(4 ,  '九游');
    INSERT  INTO  order_test ( id ,  custno)  VALUES(5 ,  '九游');
    INSERT  INTO  order_test ( id ,  custno)  VALUES(6 ,  '腾迅');
    INSERT  INTO  order_test ( id ,  custno)  VALUES(7 ,  NULL);
    
    SELECT  t1.numbers ,  COUNT(t2.id)  as  countno
    FROM  cust  t1
    LEFT  JOIN  order_test  t2  ON  t1.numbers = t2.custno
    WHERE  t1.city = '杭州'
    GROUP  BY  t1.numbers
    HAVING  count(t2.id) < 2
    ORDER  BY  countno  DESC;
    
    
    
    create  table  order1
    (
        id  NUMBER(6)  NOT NULL  primary  key,
        billno  varchar(50),
        empid  int,
        deptid  int
    )
    
    create sequence seq_order1
           minvalue 1  --最小值
           nomaxvalue --最大值
           start with 1 --起始值
           increment by 1  --增长基数
           nocycle  --不循环,一直增加
           nocache ;
    
    create trigger tri_order1_ins 
           before insert on order1 for each row  when (new.ID is null)
        begin 
          select seq_order1.nextval into:new.ID from dual;
        end;
        
      --新建职员表
    create  table  emp1
    (
        id  int,
        name  varchar(50)
    )
    create  table  dept1
    (
        id  int,
        name  varchar(50)
    )
    insert  into  dept1   select  '1' ,  '销售部' FROM dual
           union  all  select  '2' ,  '财务部' FROM dual
           union  all  select  '3' ,  '工程部' FROM dual
           union  all  select  '4' ,  '资材部' FROM dual
           union  all  select  '5' ,  '采购部' FROM dual
           union  all  select  '6' ,  '生产部' FROM dual
           union  all  select  '7' ,  '计划部' FROM dual
           union  all  select  '8' ,  '总经办' FROM dual
           union  all  select  '9' ,  '技术部' FROM dual
           union  all  select  '10' ,  '行政部' FROM dual
    --插入职员表,有5条记录
    insert  into  emp1   select  '1' ,  '李明'  FROM dual
           union  all  select  '2' ,  '陈家杰'  FROM dual
           union  all  select  '3' ,  '杨生'      FROM dual
           union  all  select  '4' ,  '李建木'    FROM dual
           union  all  select  '5' ,  '常青'      FROM dual
         BEGIN
          declare  
                cid  NUMBER(8):=1;
                cno  NUMBER(8):=1000000;
                empid  INT :=1;
                deptid  INT:=1;
          BEGIN
                while cid<=cno 
                  LOOP
                  if empid>5  THEN 
                    empid:=1;
                  END IF;
                  if deptid>10  THEN 
                    deptid:=1;
                  END IF;
                     insert  into  order1 (BILLNO,empid,deptid)  VALUES( (SELECT 'order'|| to_char(cid,'0000000') FROM dual) ,empid ,deptid );
                  cid:=cid+1;
                  empid:=empid+1;
                  deptid:=deptid+1;
                  COMMIT;
                  end loop;
           end;
           
    select  COUNT(*)/*t1.billno  as  单据编号,
    t2.name  as  职员,
    t3.name  as  部门*/
    from  order1  t1
    left  join emp1  t2  on  t1.empid=t2.id
    left  join dept1  t3  on  t1.deptid=t3.id
    
     select  COUNT(*)/*t1.billno  as  单据编号,
    t2.name  as  职员,
    t3.name  as  部门*/
    from  order1  t1
    left  join  dept1  t3  on  t1.deptid=t3.id
     left  join  emp1  t2  on  t1.empid=t2.id  

    1、多个左连接性能实验 语法1:以职员表排前面 select t1.billno as 单据编号, t2.name as 职员, t3.name as 部门 from order1 t1 left join emp1 t2 on t1.empid=t2.id left join dept1 t3 on t1.deptid=t3.id

    语法2:以部门表排前面 select t1.billno as 单据编号, t2.name as 职员, t3.name as 部门 from order1 t1 left join dept1 t3 on t1.deptid=t3.id left join emp1 t2 on t1.empid=t2.id 实验结果如下: 语法1 语法2 97秒 87秒 93秒 85秒 85秒 86秒 85秒 85秒 92秒 91秒 86秒 83秒 84秒 85秒 83秒 88秒 平均值:88.125 平均值:86.25 结论:性能上差不多。

    理论分析: 语法1 语法2 执行1(from):order1 和 emp1笛卡尔积VT1表为100000005=5千万行数据。 执行1(from):order1和dept1笛卡尔积VT1表为1000000010=10千万行数据。 执行2(on):筛选后VT2表为1千万行数据。 执行2(on):筛选后VT2表为1千万行数据。 执行3(left join):VT3表为1千万行数据。 执行3(left join):VT3表为1千万行数据。 执行4(from):VT3和dept1笛卡尔积VT4表为1000000010=10千万行数据。 执行4(from):order1 和 emp1笛卡尔积VT4表为100000005=5千万行数据。 执行5(on):筛选后VT5表为1千万行数据。 执行5(on):筛选后VT5表为1千万行数据。 执行6(left join):VT6表为1千万行数据。 执行6(left join):VT6表为1千万行数据。 理论结论:左连接性能差不多。

    2、内连接放置位置性能试验 实验之前,我们先删除4条职员数据: delete from emp1 where id in(2 , 3 , 4 , 5)

    语法1:以内联职员表放置前面 select t1.billno as 单据编号, t2.name as 职员, t3.name as 部门 from order1 t1 inner join emp1 t2 on t1.empid=t2.id left join dept1 t3 on t1.deptid=t3.id

     

    语法2:以内联职员表放置后面 select t1.billno as 单据编号, t2.name as 职员, t3.name as 部门 from order1 t1 left join dept1 t3 on t1.deptid=t3.id inner join emp1 t2 on t1.empid=t2.id

    实验结果如下: 语法1 语法2 43 35 35 35 35 36 36 39 35 35 35 35 平均值:36.5 平均值:35.83 结论:性能上差不多。

    理论分析: 语法1 语法2 执行1(from):order1 和 emp1笛卡尔积VT1表为100000001=1千万行数据。 执行1(from):order1和dept1笛卡尔积VT1表为1000000010=10千万行数据。 执行2(on):筛选后VT2表为2百万行数据。 执行2(on):筛选后VT2表为1千万行数据。 执行3(from):VT2和dept1笛卡尔积VT3表为200000010=2千万行数据。 执行3(left join):VT3表为1千万行数据。 执行4(on):筛选后VT4表为2百万行数据。 执行4(from):order1 和 emp1笛卡尔积VT4表为100000001=1千万行数据。 执行5(left join):筛选后VT5表为2百万行数据。 执行5(on):筛选后VT5表为2百万行数据。 理论结论:语法1性能优于语法2 此处发现理论结论与实验结果不同。这是什么情况?

    3、查询优化器自动优化最佳结果 查询优化器(简称优化器)是负责生成 SQL 语句的有效执行计划的 SQL Server 数据库引擎组件,具体地说,查询优化器是SQL Server针对用户的请求进行内部优化,生成(或重用)执行计划并传输给存储引擎来操作数据,最终返回结果给用户的组件。 它是关系型数据库管理系统的核心之一,决定对特定的查询使用哪些索引、哪些关联算法、从而使其高效运行,它是优化器中最重要的组件之一。

    查看语法1的实际执行计划:

     

     

     

     

     

    查看语法2的实际执行计划:

    结论:对比语法1和语法2的执行计划一模一样,所以实验结果的性能差不多。

    由于我们本次试验的查询相对较简单,故执行计划一模一样。但是,在实际情况下 可能查询语句很复杂,数据量很庞大的情况下,执行计划有时候也不灵验,需要我们对连接顺序进行调整优化,如早期写的一个SQL语句: select t1.FBillNo , t1.FInterID , t2.FEntryID , t1.FCustID , t6.FBillNo as FOutBillNo, t7.fbillno as FWWBillNo_New , t8.FItemID , t4.FErpClsID , t8.FBatchNo , t2.FAuxQty , t8.FAuxPrice , t2.FAuxQty * t8.FAuxPrice as FAmount , 2 as CBType from SEOrder t1 inner join SEOrderEntry t2 on t1.FInterID=t2.FInterID inner join t_ICItem t4 on t2.FItemID=t4.FItemID inner join t_Organization t5 on t5.FItemID=t1.FCustID left join ( select t061.FOrderInterID , t061.FOrderEntryID , t062.FBillNo from ICStockBillEntry t061 inner join ICStockBill t062 on t061.FInterID=t062.FInterID where t062.FTranType=21 and t061.FAuxPrice<>0 ) t6 on t2.FInterID=t6.FOrderInterID and t2.FEntryID=t6.FOrderEntryID inner join #tmp1 t7 on t7.fitemid =t2.FItemID inner join ( select t081.FItemID , t081.FBatchNo , t082.FBillNo , t081.FAuxPrice from ICStockBillEntry t081 inner join ICStockBill t082 on t081.FInterID=t082.FInterID where t082.FTranType=5 ) t8 on t8.FBillNo=t7.FBillNo and t8.FItemID=t7.FItemID and t8.FBatchNo=t7.FBatchNo where (1=1) and t1.FStatus>0 and t1.FCancellation=0 and t1.FBillNo >= @FBillNo1 and t1.FBillNo <= case when @FBillNo2='' then (select MAX(FBillNo) from SEOrder) else @FBillNo2 end and t4.FNumber >= @FNumber1 and t4.FNumber <= case when @FNumber2='' then (select MAX(FNumber) from t_ICItem) else @FNumber2 end and t5.FNumber >= @FCustID1 and t5.FNumber <= case when @FCustID2='' then (select MAX(FNumber) from t_Organization) else @FCustID2 end and t1.FDate >= @FDate1 and t1.FDate <= case when @FDate2='' then '2100-1-1' else @FDate2 end and t6.FBillNo is null

    4、为什么理论的原理没效果呢? 绝大多数情况下,在MS SQL Server或Oracle这两个最主流的大型数据库中,在近几年的版本中,单条语句中,Where条件中,各条件的顺序对查询的效率、速度,没有明显影响。MS SQL Server或Oracle已经考虑到了Where条件的优化,它们会对这些条件进行智能分析,进行最佳的方式查询。

    网络上所传Where对性能有影响的说法,要么是针对过往老旧的数据库系统而言,要么就是想当然,要么就是对一些特定的小数据库系统或设计不够好的数据库系统而言的,至少,对当前主流版本的MS SQL Server或Oracle,这种说法是错的。

    但是,在多语句,特别是使用临时表进行查询的情况下,每条语句的结果是需要设计者认真分析的,要尽可能减少中间数据量,以达到最大效率。

    如果你不相信,可以自已亲自去MS SQL Server或Oracle中试试,建议MS SQL Server 2008 R2以上版本 或 Oracle 10G 以上版本中,数据量大于10万条记录中,以两个会带来较大记录条数差别的条件,改变它们在where中的顺序去查,你会发现,查询所需时间基本上是一样的(请多次重复,并最好在没有干扰的情况下)。

    最后想说,IT技术发展到现在,这些问题,大型公司早就考虑到了的。

    5、百万级数据库优化方案 1.对查询进行优化,要尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。

    2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null 最好不要给数据库留NULL,尽可能的使用 NOT NULL填充数据库。 备注、描述、评论之类的可以设置为 NULL,其他的,最好不要使用NULL。

    不要以为 NULL 不需要空间,比如:char(100) 型,在字段建立时,空间就固定了, 不管是否插入值(NULL也包含在内),都是占用 100个字符的空间的,如果是varchar这样的变长字段, null 不占用空间。 可以在num上设置默认值0,确保表中num列没有null值,然后这样查询: select id from t where num = 0

    3.应尽量避免在 where 子句中使用 != 或 <> 操作符,否则将引擎放弃使用索引而进行全表扫描。

    4.应尽量避免在 where 子句中使用 or 来连接条件,如果一个字段有索引,一个字段没有索引,将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num=10 or Name = 'admin' 可以这样查询: select id from t where num = 10 union all select id from t where Name = 'admin'

    5.in 和 not in 也要慎用,否则会导致全表扫描,如: select id from t where num in(1 , 2 , 3)

    对于连续的数值,能用 between 就不要用 in 了: select id from t where num between 1 and 3

    很多时候用 exists 代替 in 是一个好的选择: select num from a where num in(select num from b) 用下面的语句替换: select num from a where exists(select 1 from b where num=a.num)

    6.下面的查询也将导致全表扫描: select id from t where name like '%abc%' 若要提高效率,可以考虑SQL的全文检索技术。 另一种做法:根据输入条件,先查询和确定符合条件的结果,并把相关记录保存在一个临时表中,然后再用临时表去做复杂关联。

    7.如果在 where 子句中使用参数,也会导致全表扫描。因为SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择。然 而,如果在编译时建立访问计划,变量的值还是未知的,因而无法作为索引选择的输入项。如下面语句将进行全表扫描: select id from t where num = @num 可以改为强制查询使用索引: select id from t with(index(索引名)) where num = @num

    8.应尽量避免在 where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描。如: select id from t where num/2 = 100 应改为: select id from t where num = 100*2

    9.应尽量避免在where子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描。如: select id from t where substring(name , 1 , 3) = ’abc’ --name以abc开头的id

    select id from t where datediff(day , createdate , ’2005-11-30') = 0 --'2005-11-30’ --生成的id

    应改为: select id from t where name like 'abc%' select id from t where createdate >= '2005-11-30' and createdate < '2005-12-1'

     

    10.不要在 where 子句中的“=”左边进行函数、算术运算或其他表达式运算,否则系统将可能无法正确使用索引。

    11.在使用索引字段作为条件时,如果该索引是复合索引,那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使用,并且应尽可能的让字段顺序与索引顺序相一致。

    12.不要写一些没有意义的查询,如需要生成一个空表结构: select col1 , col2 into #t from t where 1=0 这类代码不会返回任何结果集,但是会消耗系统资源的,应改成这样: create table #t(…)

    13.Update 语句,如果只更改1、2个字段,不要Update全部字段,否则频繁调用会引起明显的性能消耗,同时带来大量日志。

    14.对于多张大数据量(这里几百条就算大了)的表JOIN,要先TOP分页再JOIN,否则逻辑读会很高,性能很差。

    1. select count(*) from table;这样不带任何条件的count会引起全表扫描,并且没有任何业务意义,是一定要杜绝的。

    16.索引并不是越多越好,索引固然可以提高相应的 select 的效率,但同时也降低了 insert 及 update 的效率,因为 insert 或 update 时有可能会重建索引,所以怎样建索引需要慎重考虑,视具体情况而定。一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有 必要。

    17.应尽可能的避免更新 clustered 索引数据列,因为 clustered 索引数据列的顺序就是表记录的物理存储顺序,一旦该列值改变将导致整个表记录的顺序的调整,会耗费相当大的资源。若应用系统需要频繁更新 clustered 索引数据列,那么需要考虑是否应将该索引建为 clustered 索引。

    18.尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连 接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。

     

    19.尽可能的使用 varchar/nvarchar 代替 char/nchar ,因为首先变长字段存储空间小,可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些。

    20.任何地方都不要使用 select * from t,用具体的字段列表代替“*”,不要返回用不到的任何字段。

    21.尽量使用表变量来代替临时表。如果表变量包含大量数据,请注意索引非常有限(只有主键索引)。

    1. 避免频繁创建和删除临时表,以减少系统表资源的消耗。临时表并不是不可使用,适当地使用它们可以使某些例程更有效,例如,当需要重复引用大型表或常用表中的某个数据集时。但是,对于一次性事件, 最好使用导出表。

    23.在新建临时表时,如果一次性插入数据量很大,那么可以使用 select into 代替 create table,避免造成大量 log ,以提高速度;如果数据量不大,为了缓和系统表的资源,应先create table,然后insert。

    24.如果使用到了临时表,在存储过程的最后务必将所有的临时表显式删除,先 truncate table ,然后 drop table ,这样可以避免系统表的较长时间锁定。

    25.尽量避免使用游标,因为游标的效率较差,如果游标操作的数据超过1万行,那么就应该考虑改写。

    26.使用基于游标的方法或临时表方法之前,应先寻找基于集的解决方案来解决问题,基于集的方法通常更有效。

    27.与临时表一样,游标并不是不可使用。对小型数据集使用 FAST_FORWARD 游标通常要优于其他逐行处理方法,尤其是在必须引用几个表才能获得所需的数据时。在结果集中包括“合计”的例程通常要比使用游标执行的速度快。如果开发时 间允许,基于游标的方法和基于集的方法都可以尝试一下,看哪一种方法的效果更好。

    28.在所有的存储过程和触发器的开始处设置 SET NOCOUNT ON ,在结束时设置 SET NOCOUNT OFF 。无需在执行存储过程和触发器的每个语句后向客户端发送 DONE_IN_PROC 消息。 29.尽量避免大事务操作,提高系统并发能力。

    30.尽量避免向客户端返回大数据量,若数据量过大,应该考虑相应需求是否合理。

    实际案例分析:拆分大的 DELETE 或INSERT 语句,批量提交SQL语句   如果你需要在一个在线的网站上去执行一个大的 DELETE 或 INSERT 查询,你需要非常小心,要避免你的操作让你的整个网站停止相应。因为这两个操作是会锁表的,表一锁住了,别的操作都进不来了。   Apache 会有很多的子进程或线程。所以,其工作起来相当有效率,而我们的服务器也不希望有太多的子进程,线程和数据库链接,这是极大的占服务器资源的事情,尤其是内存。   如果你把你的表锁上一段时间,比如30秒钟,那么对于一个有很高访问量的站点来说,这30秒所积累的访问进程/线程,数据库链接,打开的文件数,可能不仅仅会让你的WEB服务崩溃,还可能会让你的整台服务器马上挂了。   所以,如果你有一个大的处理,你一定把其拆分,使用 LIMIT oracle(rownum), sqlserver(top)条件是一个好的方法。下面是一个mysql示例: while(1){   //每次只做1000条    mysql_query(“delete from logs where log_date <= ’2012-11-01’ limit 1000”);   if(mysql_affected_rows() == 0){      //删除完成,退出!      break;   } //每次暂停一段时间,释放表让其他进程/线程访问。 usleep(50000) }

  • 相关阅读:
    python中读取文件数据时要注意文件路径
    sklearn.model_selection 的 train_test_split作用
    matplotlib中subplot的各参数的作用
    用梯度下降算法求最值
    AfxMessageBox与MessageBox用法与区别
    MFC、API、C++三者的区别
    2、CString与string借助char *互转
    1、创建MFC应用程序——单个文档
    1、Mat类的属性、方法
    CMake编译OpenCV
  • 原文地址:https://www.cnblogs.com/chenzhelove/p/13483141.html
Copyright © 2011-2022 走看看