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

相关内容

    暂无相关文章