如何结合这里提到的查询?

时间:2013-03-06 15:09:38

标签: sql oracle plsql

这里我有两个名为main_tablemain_table_replica的表。 main_table_replicamain_table的副本。但问题是我可以在main_tablemain_table_replica中找到数据。 现在我正在进行如下查询。我怎么能避免在这里结合?在这两个查询中,唯一的更改是main_tablemain_table_replica

SELECT DISTINCT e.some_id
         FROM
             main_table e,   //Change is here
             main_table_join_one x     
             where  e.some_id = x.some_id(+)
             and (x.status in('A','I') or x.status is null)
             and e.code='XYZ' and e.second_code in('XYZ','ABC')


             UNION

        SELECT DISTINCT t.some_id
         FROM
             main_table_replica t,   //Change is here
             main_table_join_one xf     
             where  t.some_id = xf.some_id(+)
             and (xf.status in('A','I') or xf.status is null)
             and t.code='XYZ' and t.second_code in('XYZ','ABC')  

谢谢!

1 个答案:

答案 0 :(得分:2)

以这种方式从两个不同的表中获取内容正是union的用途。没有理由避免它。

但是,您可以缩小联合的范围以减少重复:

select distinct combined.some_id from (
        select e.some_id from main_table e
            union
        select t.some_id from main_table_replica t
    ) combined
    inner join  main_table_join_one x on
        combined.some_id = x.some_id(+) and
        (x.status in('A','I') or x.status is null) and
        combined.code='XYZ' and 
        combined.second_code in('XYZ','ABC');