由于相关子查询
,我有一个性能较差的查询,我想替换它
非相关子查询
。如何做到这一点:
我的查询:
select a.emp_num, a.name , b.cont_date
from main_emp a INNER JOIN main_cont b
ON a.emp_num = b.emp_num AND a.calc_year = b.calc_year
join
(
select emp_num,calc_year, max(bb.cont_date) AS max_date from main_cont bb
GROUP BY emp_num,calc_year
) bb_max
on a.emp_num = bb_max.emp_num and a.calc_year = bb_max.calc_year and b.cont_date = bb_max.max_date
where
( 0 = ( select count(*) from main_serv x where x.emp_num = a.emp_num and x.calc_year = a.calc_year )
or b.cont_date > ( select max(y.ser_date) from main_serv y where y.emp_num = a.emp_num and y.calc_year = a.calc_year) ) -- The problem here
and a.calc_year = 2015
order by 1
现在我想转换这个子查询:
( 0 = ( select count(*) from main_serv x where x.emp_num = a.emp_num and x.calc_year = a.calc_year )
or b.cont_date > ( select max(y.ser_date) from main_serv y where y.emp_num = a.emp_num and y.calc_year = a.calc_year) )
至
像这样加入:
join
(
select emp_num,calc_year, max(bb.cont_date) AS max_date from main_cont bb
GROUP BY emp_num,calc_year
) bb_max
on a.emp_num = bb_max.emp_num and a.calc_year = bb_max.calc_year and b.cont_date = bb_max.max_date
但我不知道如何执行此操作,因为我有 ((0 =(subquery) OR (subquery))
最佳答案
我相信你的 WHERE 子句的这一部分
( 0 = ( select count(*) from main_serv x where x.emp_num = a.emp_num and x.calc_year = a.calc_year )
or b.cont_date > ( select max(y.ser_date) from main_serv y where y.emp_num = a.emp_num and y.calc_year = a.calc_year) )
可以呈现为
There are no rows in
main_serv
OR
There are no rows inmain_serv
whereser_date
is equal to or greater thanb.cont_date
.
我相信析取的第二部分涵盖了完整的条件,因为当 main_serv
中没有行时,肯定不会有与条件的第二部分匹配的行,并且如果有main_serv
中的任何行,它将是确定结果的条件的第二部分。因此,我将重写整个析取部分,如下所示:
not exists (
select *
from main_serv as x
where x.emp_num = a.emp_num
and x.calc_year = a.calc_year
and x.ser_date >= b.cont_date
)
此子查询仍然与主查询相关,但它不会执行任何聚合,并且总体上可能比您的版本有所改进。
关于sql - 如何用非相关子查询替换相关子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20934780/