简体   繁体   English

将相关子查询转换为JOIN

[英]Converting a correlated sub-query to JOIN

I have a correlated subquery which is creating performance issues. 我有一个相关的子查询,这会造成性能问题。 Being a correlated subquery it doesn't accept index hints either. 作为相关子查询,它也不接受索引提示。 So I am trying to convert it into a JOIN instead. 因此,我尝试将其转换为JOIN。 Please find below the original query and the modified query. 请在下面找到原始查询和修改后的查询。 The modified query doesn't return any row but the original returns me 224 rows. 修改后的查询不会返回任何行,但原始查询会返回224行。

Appreciate any insight on what is wrong with my JOIN query, if it even makes sense to use JOIN instead of subquery in this case. 如果在这种情况下使用JOIN代替子查询甚至有意义,请对我的JOIN查询出什么问题的任何见解表示赞赏。 Thanks. 谢谢。

select Area_CODE,
       due_DATE,
       RATE,

from SCHED S
where (s.Area_CODE = 11001 and 
   (s.COMP_CODE = 'a' 
   or
      (s.COMPANY_CODE = 'b' 
          and s.due_DATE <
          (
           select
               nvl( min(s1.due_DATE), to_date  ( '31-DEC-2999', 'DD-MM-YYYY') )
               from   SCHED s1
               where  s1.AREA_CODE = s.AREA_CODE 
               and s1.COMP_CODE = 'c'
          )
       )
    )
   )
order by a.EFF_DATE asc, s.due_DATE asc

Modified Query: 修改后的查询:

SELECT
  Area_CODE,
       due_DATE,
       RATE

from SCHED S
LEFT JOIN
  (
    SELECT
      NVL( MIN(s1.due_DATE), to_date ( '31-DEC-2999', 'DD-MM-YYYY') ) AS
      min_date,
      s1.AREA_CODE AS a_code
    FROM
      SCHED s1
    WHERE
      s1.COMPANY_CODE = 'c'
    GROUP BY
      s1.AREA_code
  )
  s2
ON
  s2.A_CODE = s.area_code
WHERE
  (
    s.area_code = 11001
  AND
    (
      s.COMP_CODE = 'a'
    OR
      (
        s.COMP_CODE = 'b' 
      and s.due_DATE < s2.min_date
      )
    )
  )
order by s.EFF_DATE asc, s.due_DATE asc

The difference is where there are no dates for a given area code 区别在于给定区号没有日期的地方

Change the left join (s2) to an inner join on 将左侧联接(s2)更改为内部联接

inner JOIN 
( 
    SELECT 
        min(s1.due_DATE) AS min_date, 
        s1.AREA_CODE AS a_code 
    FROM 
        (
            select Area_Code, due_date from SCHED WHERE COMPANY_CODE = 'c' 
            union
            select Area_Code, to_date('31-dec-2999','DD-MM-YYYY') from SCHED
        ) s1    
    GROUP BY 
        s1.AREA_code 
) s2 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM