【发布时间】:2011-04-04 03:00:09
【问题描述】:
假设master_table包含许多记录,并且master_table的“id”字段,tableA,tableB,tableC和tableD在商业意义上是相同的。
对于如下所示的 2 个选择语句,
它们会返回相同的结果集吗?
哪一个会有更好的表现?
我认为如果 tableA_tmp ,tableB_tmp,tableC_tmp 和 tableD_tmp 返回一个较小的结果集,SQL1 会比 SQL2 快,因为 oracle 不需要为每个 master_table 记录查询 tableA_tmp,,tableB_tmp,tableC_tmp 和 tableD_tmp 一次。
但是如果 tableA_tmp,tableB_tmp,tableC_tmp 和 tableD_tmp 都返回大结果集,SQL 2 会快得多,因为加入许多大结果集的成本远高于查询 tableA_tmp,,tableB_tmp,tableC_tmp 和 tableD_tmp 一次每个 master_table 记录。
如果我有任何误解,请纠正我。还是建议的其他方法?
SQL1:
select
master_table.* ,
tableA_tmp.cnt as tableA_cnt ,
tableB_tmp.cnt as tableB_cnt ,
tableC_tmp.cnt as tableC_cnt ,
tableD_tmp.cnt as tableD_cnt
from
master_table,
(select tableA.id as id, count(1) as cnt from tableA group by tableA.id) tableA_tmp,
(select tableB.id as id, count(1) as cnt from tableB group by tableB.id) tableB_tmp,
(select tableC.id as id, count(1) as cnt from tableC group by tableC.id) tableC_tmp,
(select tableD.id as id, count(1) as cnt from tableD group by tableD.id) tableD_tmp
where
master_table.id = tableA_tmp.id(+) and
master_table.id = tableB_tmp.id(+) and
master_table.id = tableC_tmp.id(+) and
master_table.id = tableD_tmp.id(+) ;
SQL 2:
select
master_table.* ,
(select count(*) from tableA where tableA.id = master_table.id) as tableA_cnt,
(select count(*) from tableB where tableB.id = master_table.id) as tableB_cnt,
(select count(*) from tableC where tableC.id = master_table.id) as tableC_cnt,
(select count(*) from tableD where tableD.id = master_table.id) as tableD_cnt
from
master_table;
【问题讨论】:
-
真的值得一试吗?
标签: sql performance oracle select