zoukankan      html  css  js  c++  java
  • Oracle中Left join的on和where的效率差别

    假设有两个表a、b

    使用on

    Select * from a left join b on b.col = a.col and b.col2 = ‘aa’

    使用 where

    Select * from a left join b on b.col = a.col where b.col2 = ‘aa’ and b.col2 is null

    // b.col2 is null作用是防止因b表中没有匹配数据,照成a表原有记录无法返回的问题

    分析

    1、on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。

    2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。

    语句测试

    set serveroutput on ; -- 必须运行,否则打印结果无法显示

    declare

    I Number;

    Starttime Timestamp;

    Endtime Timestamp;

    Begin

    select current_timestamp(5) into starttime from Dual;

    I := 1;

    While I<=10000 Loop 

          dbms_output.put_line(i);

          Execute Immediate ' '; --此处放入sql语句

          i := i+1;

    End Loop;

    Select Current_Timestamp(5) Into Endtime From Dual;

    dbms_output.put_line('10000条语句运行时间为(毫秒):' || (endtime - starttime)); --打印一个Interval类型数据,显示时间差

    end;

    测试结果

    On语句, 10000条语句运行时间为(毫秒):+000000000 00:00:01.032850000

    Where 语句 10000条语句运行时间为(毫秒):+000000000 00:00:01.013420000

     

    结论

    Where语句的性能优于on语句

    其实sql语句的运行效率也可以通过查询oracle的系统视图来查看,但时间关系今后再研究了。

    在C#中使用linq进行查询

    // 写得比较仓促,见谅了

    var reList = from DataRow a in dtA.Rows

                join DataRow b in dtB.Rows on

                    new {t = a["col"], l=’aa’}

                    equals

                    new {t = b["col"], l = b["col2"] }

                    into rightRow from rw in rightRow.DefaultIfEmpty()

                    select new

                    {

                         Col1 = a["col"],

                         Col2 = rw["col2"]

                     };

    在linq中使用into rightRow from rw in rightRow.DefaultIfEmpty()可以保证查询类型left outer join的效果,如果left join中有多个查询条件,使用new两个对象进行比较即可。

  • 相关阅读:
    Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments环境代码详解
    zc.buildout构建项目时报错‘AttributeError: '_NamespacePath' object has no attribute 'sort'’
    利用Jenkins打包ISO和QCOW2镜像文件
    解决python pip安装提示"not a supported wheel on this platform"
    Kali 2017.3开启VNC远程桌面登录
    Jenkins邮件扩展插件Email Extension Plugin配置使用
    Jenkins执行sudo权限的设置
    如何解决源码安装软件中make时一直重复打印configure信息
    CentOS 7下安装配置proftpd搭建ftp服务器
    如何使用capedit分割数据包文件
  • 原文地址:https://www.cnblogs.com/smallidea/p/3609382.html
Copyright © 2011-2022 走看看