暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

【干货攻略】SQL优化之-LIKE CASE WHEN改写思路(二)

达梦E学 2024-12-06
120

引 言

case when条件判断与or之间的等价替换思考。

本章内容已在如下环境上测试:
①数据库版本:达梦DM8。
相关关键字:SQL优化 ,case when

——正文——

01

构造案例

构造数据

    SQL> drop table if exists tt1; 
    SQL> create table tt1 (id varchar2(20) primary key,code varchar2(4),c2 varchar2(20),ll int);
    SQL> insert into tt1 select 'A'||level,'0'||to_char(round(dbms_random.value(300,320),0)),'C'||to_char(round(dbms_random.value(1,5000),0)),2
    from dual connect by level<=20000;
    SQL> insert into tt1 select 'A'||level+200000,'03','C'||to_char(round(dbms_random.value(1,5000),0)),1
    from dual connect by level<=100;
    commit;
      SQL> drop table if exists tt2; 
      SQL> create table tt2 (id varchar2(20) primary key,code varchar2(4),ll int);
      SQL> insert into tt2 select 'A'||level,'0'||to_char(round(dbms_random.value(1,10),0)),2
      from dual connect by level<=10;
      SQL> insert into tt2 select 'A'||level+10000,'0'||to_char(round(dbms_random.value(300,320),0)),2
      from dual connect by level<=10;
      commit;

      搜集表的统计信息:

        dbms_stats.gather_table_stats('SYSDBA','TT1',null,100);
        dbms_stats.gather_table_stats('SYSDBA','TT2',null,100);

        创建索引:

          create index IDX_DM_TT1_CODE on tt1(code);
          create index IDX_DM_TT2_CODE on tt2(code);

          查看执行计划:

            SQL> set autotrace traceonly
            select count(*)
            from tt1, tt2
            where (tt1.code like case
            when tt1.ll = 1 then
            tt2.code
            when tt1.ll = 2 then
            tt2.code || '%'
            end);

            02

            技术分析

            语句中的性能问题在于like case when做成笛卡尔积。

            case when用于条件判断,语句用业务角度理解,假设ll是层级的意思,第一(基层)层级就获取本级别的数据;第二层级有权限获取下级的数据,做like关联获取本级及下级数据。最终展示两个层级的所有数据,就是层级1+层级2数据.

            另外条件判断,要么满足条件1,要么满足条件2,or运算也属于条件判断,那么case when也可以改写成or。

            SQL改写:

              SQL> select
              count(*)
              from tt1, tt2
              where (tt1.ll = 1 and tt1.code = tt2.code)
              or (tt1.ll = 2 and tt1.code like tt2.code || '%');


              总结


              语句where中出现case when判断,一般可以改写成or方式和union all方式,另外在等价改写中要注意等价替换,确保逻辑上是成立。



              END


              以上为本期分享,希望能带给大家帮助。想要了解更多往期干货,可访问页面最下方#达梦技术干货攻略#合集或下方相关分享。在此邀请更多学员参与“达梦技术干货投稿活动”,稿件获选后将在达梦“干货分享”专栏进行发布,欢迎来稿!


              往期回顾


              【干货攻略】SQL优化之-LIKE CASE WHEN改写思路(一)

              【干货攻略】达梦报错超长记录如何分析

              【干货攻略】DM8在线重定义表

              【开班通知】第35期DM8-DCP线上培训班招生中

              【开班通知】第37期DM8-DCA线上培训班招生中



              达梦E学
              达梦数据  学习园地


              文章转载自达梦E学,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

              评论