sql - 如何用非相关子查询替换相关子查询?

标签 sql performance subquery informix

由于相关子查询,我有一个性能较差的查询,我想替换它 非相关子查询。如何做到这一点:

我的查询:

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 in main_serv where ser_date is equal to or greater than b.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/

相关文章:

java嵌入式库磁盘键值数据库

java - 关于 jpa/hibernate subselect 获取的询问

sql-server - SQL Server 左连接

mysql - 子查询的 rand() 列针对 MySQL 5.7/8.0 与 MySQL 5.6 中的每个重复选择重新评估

mysql - 计算贷款支付以及支付何时得到满足 - 允许部分支付

sql - 如果 SQL Server 中先前的单元格值和当前单元格值相同,则选择空

php - SQL SELECT 一个字符串中的一个词与另一个字符串中的一个词匹配

sql - 是否可以使用 Entity Framework 运行 native sql?

python - 为什么整数指数的 numpy.power 更慢?

c# - C#两个几乎相同的线程,性能差异很大