大神们,这个SQL如下,搞了半天都没有搞定,感觉很奇怪,给大神跪了ORZ
select v.*,
(select count(*) from Table1 t where t.Column1 = v.Column3) alias1,
(select count(*) from Table1 t where t.Column2 = v.Column4) alias2
from Table2 v
where (
Condition1 between trunc(sysdate, 'dd') - 1 and trunc(sysdate, 'dd') + 2
or
Condition2 between trunc(sysdate, 'dd') - 1 and trunc(sysdate, 'dd') + 2
)
------解决方案--------------------
请提供执行计划
看语句应该是
(select count(*) from Table1 t where t.Column1 = v.Column3) alias1,
(select count(*) from Table1 t where t.Column2 = v.Column4) alias2
这两个子查询耗时较多
------解决方案--------------------
改为这样试试,不行的话请提供执行计划,针对性优化
select v.*,A.alias1,B.alias2
from
(select Column1,count(*) as alias1 from Table1 group by Column1) A,
(select Column2,count(*) as alias2 from Table1 group by Column2) B,
Table2 v
where A.Column1 = v.Column3 and B.Column2 = v.Column4
and(Condition1 between trunc(sysdate, 'dd') - 1 and trunc(sysdate, 'dd') + 2
or Condition2 between trunc(sysdate, 'dd') - 1 and trunc(sysdate, 'dd') + 2)
------解决方案--------------------
应该是关联条件的事,改为右连接,应该就好了
A.Column1 = v.Column3(+) and B.Column2 = v.Column4(+)
------解决方案--------------------
如果Table2中存在某些记录在Table1中找不到对应的记录,这些记录用原来的语句是查不出来的,改为右连接应该就可以了
------解决方案--------------------
这个or 有问题啊
是不是应该这样
select v.*,A.alias1,B.alias2
from
(select Column1,count(*) as alias1 from Table1 group by Column1) A,
(select Column2,count(*) as alias2 from Table1 group by Column2) B,
Table2 v
where A.Column1 = v.Column3 and B.Column2 = v.Column4
and((Condition1 between trunc(sysdate, 'dd') - 1 and trunc(sysdate, 'dd') + 2)
or (Condition2 between trunc(sysdate, 'dd') - 1 and trunc(sysdate, 'dd') + 2))
------解决方案--------------------

------解决方案--------------------
这么谦虚,呵~
sql调优方面,以前很在意写法带来的性能差异,但现在偏向于从数据量,索引的角度看.