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两个对象进行比较即可。

  • 相关阅读:
    [CF837B] Flag of Berland(乱写)
    [Uva12563] Jin Ge Jin Qu hao (完全背包,dp)
    [BZOJ2818] Gcd (数论,欧拉函数,线性筛)
    [CF777E] Hanoi Factory(贪心,栈)
    [CF777D] Cloud of Hashtags(贪心,二分)
    [CF777C] Alyona and Spreadsheet(dp)
    [BZOJ2440][中山市选2011]完全平方数(莫比乌斯函数,二分)
    [CF821C] Okabe and Boxes(模拟,栈)
    Codeforces Round #363 (Div. 2)->B. One Bomb
    Codeforces Round #363 (Div. 2)->A. Launch of Collider
  • 原文地址:https://www.cnblogs.com/smallidea/p/3609382.html
Copyright © 2011-2022 走看看