将相关子查询转换为JOIN

时间:2012-07-19 21:01:34

标签: sql oracle11g

我有一个相关的子查询,它会产生性能问题。作为相关子查询,它也不接受索引提示。所以我试图将其转换为JOIN。请在下面找到原始查询和修改后的查询。修改后的查询不返回任何行,但原始返回224行。

如果在这种情况下使用JOIN而不是子查询甚至是有意义的,请理解我的JOIN查询有什么问题。感谢。

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

修改后的查询:

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

1 个答案:

答案 0 :(得分:0)

区别在于没有给定区号的日期

将左连接(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