【问题标题】:SQL: Selecting between datesSQL:在日期之间进行选择
【发布时间】:2014-06-30 13:23:24
【问题描述】:

我有两个看起来像这样的表:

table A:
ID, target_date, target_ID

table B:
ID, target_ID, begin_date, end_date

表 B 可能具有相同 target_ID 但不同日期范围的多条记录。我对能够返回不在给定 target_ID 的 begin_date 和 end_date 范围内的 target_dates 的 SQL 查询感兴趣。

【问题讨论】:

  • 你能提供你已经尝试过的样品吗?
  • 可能没那么重要,但您应该为您正在使用的 DBMS 添加一个标签(Postgres、Oracle、...)

标签: sql database


【解决方案1】:

这有一个技巧。使用left join 查找匹配的,然后选择不匹配的:

select a.*
from tablea a left join
     tableb b
     on a.target_id = b.target_id and
        a.target_date between b.begin_date and b.end_date
where b.target_id is null;

您可以用几种不同的方式表达这一点。例如,not exists 也可能看起来很自然:

select a.*
from tablea a
where not exists (select 1
                  from tableb b
                  where a.target_id = b.target_id and
                        a.target_date between b.begin_date and b.end_date
                 );

注意:我在这些比较中使用between 作为方便的速记(以匹配您在问题中使用的语言)。通常带有日期,最好明确使用<<=>>=

【讨论】:

    【解决方案2】:
    SELECT A.target_date 
    FROM A LEFT OUTER JOIN B 
         ON (A.target_ID=B.target_ID 
         AND A.target_date>=B.begin_date 
         AND A.target_date<=B.end_date) 
    WHERE B.begin_date IS NULL
    

    【讨论】:

      【解决方案3】:

      也许:

      SELECT target_date FROM A 
         INNER JOIN B 
         ON A.target_ID = B.target_ID
      WHERE target_date NOT BETWEEN begin_date AND end_date
      

      【讨论】:

        猜你喜欢
        • 2012-05-04
        • 2012-03-12
        • 2012-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 2019-10-09
        相关资源
        最近更新 更多