简化嵌套查询

问题描述 投票:3回答:1

我想获取在给定日期(基于id_external)添加和删除的记录,所以我使用了下面的查询,这给了我预期的结果但是它花费了很多时间并且LOGICALREAD太高了,...有人可以简化它

SELECT ar.*
      FROM t_row_data ar
      WHERE ar.id_instance     IS NULL
      AND ar.id_category     IS NULL
      AND ar.source_name      ='SomeSource'
      AND ar.eco_date        IN (date '2017-12-22', date '2017-12-21')
      AND ar.active           = 'Y'
      AND ar.id_external IN 
        (SELECT ar.id_external
              FROM t_row_data ar
              WHERE ar.id_instance     IS NULL
              AND ar.id_category     IS NULL
              AND ar.source_name      ='SomeSource'
              AND ar.eco_date        IN (date '2017-12-22', date '2017-12-21')
              AND ar.active           = 'Y'
              GROUP BY ar.id_external
              HAVING COUNT(1) = 1)
sql oracle nested
1个回答
1
投票

假设表t_row_data有列id_external, id_instance, id_category, source_name, eco_date, active, col7, col8, ...,你可以像这样重写查询:

select   id_external, null as id_instance, null as id_category,
         'SomeSource' as source_name, max(eco_date) as eco_date, 'Y' as active,
         max(col7) as col7, max(col8) as col8, ...
from     t_row_data
where    id_instance is null
  and    id_category is null
  and    source_name = 'SomeSource'
  and    eco_date    between date '2017-12-21' and date '2017-12-22'
  and    active      = 'Y'
group by id_external
having   count(*) = 1
;
© www.soinside.com 2019 - 2024. All rights reserved.