【问题标题】:union tables where date日期的联合表
【发布时间】:2017-04-28 16:00:24
【问题描述】:

我需要查询 Oracle 数据库中的 2 个表。一个是当前表,另一个是历史表,具有几乎相同的标题。我希望能够对查询进行联合,但只有一个日期范围。 我正在尝试做的一个简单示例可能是一个更好的解释:

select order_number, insertdate        
from do_table      
where insertdate between '1-apr-17' and '8-apr-17'   
union  
select order_number, insertdate  
from doi_table  
where insertdate between '1-apr-17' and '8-apr-17'

可以这样写吗?

select order_number, insertdate  
from do_table  
union  
select order_number, insertdate  
from doi_table  
where insertdate between '1-apr-17' and '8-apr-17'

查询的日期范围变化很​​大,查询量很大,为了方便,我希望运行查询的用户能够输入一次日期范围。

有什么建议吗?

谢谢

【问题讨论】:

    标签: sql oracle union date-range


    【解决方案1】:

    如果您只想在需要创建子查询时使用 where。

    SELECT *
    FROM (
        select order_number, insertdate  
        from do_table  
        union  
        select order_number, insertdate  
        from doi_table  
        ) T
    WHERE insertdate between '1-apr-17' and '8-apr-17'
    

    但我不推荐它,因为那样您将无法从 insertdate 字段上的索引中受益。你的第一个查询没问题,只需使用两次用户参数

    【讨论】:

      【解决方案2】:

      处理此问题的一种方法是使用params CTE:

      with params as (
            select date '2017-04-01' as date1, date '2017-04-08' as date2
            from dual
           )
      select t.order_number, t.insertdate        
      from params cross join do_table t     
      where t.insertdate between params.date1 and params.date2 
      union all
      select t.order_number, t.insertdate  
      from params cross join doi_table  t 
      where t.insertdate between params.date1 and params.date2 ;
      

      请注意,我将 union 更改为 union allunion 会产生额外的删除重复项的开销。如果您打算这样做,请使用union。但默认情况下,union all 更好。

      我应该补充一点,根据我的经验,从性能角度来看,这样的 params CTE 很好,但也可能有例外。

      【讨论】:

      • 我知道英语是我的第一语言。但是CTE is find from a performance 听起来不太好。不确定您是说性能好还是坏。
      • @JuanCarlosOropeza 。 . .我猜英语是不是你的第一语言。无论如何,“d”就在键盘上的“e”旁边。
      猜你喜欢
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多