【问题标题】:SQL join greater than / less thenSQL join 大于/小于 then
【发布时间】:2020-02-16 17:49:26
【问题描述】:

我有两张桌子

我 所以我需要得到一个表,其中将排除每个“id”的日期比第二个表“datestop”中的日期多的行

我尝试了双重条件的内部连接: id = id and Date

想象一下,这就是我想要得到的:

【问题讨论】:

  • 请在代码问题中给出minimal reproducible example--剪切&粘贴&运行代码;具有期望和实际输出(包括逐字错误消息)的示例输入(作为初始化代码);标签和版本;明确的规范和解释。对于包含您可以提供的代码最少的错误,即您显示的代码可以通过您显示的代码扩展为不正常。 (调试基础。)How to Ask 适用于包括版本和 DDL 的 SQL,其中包括约束、索引和表格初始化。请use text, not images/links, for text--including tables & ERDs.

标签: sql date join left-join inner-join


【解决方案1】:

我会使用NOT EXISTS,这非常有效:

select t1.*
from table1 t1
where not exists ( 
  select 1 from table2 t2 
  where t2.id = t1.id and t2.datestop <= t1.date  
)

不清楚您是否需要 Status 的值必须为 'Stopped' 才能满足您的要求。
所以也许你需要把子查询的WHERE子句改成:

where t2.id = t1.id and t2.datestop <= t1.date and t2.status = 'Stopped'

【讨论】:

    【解决方案2】:

    考虑:

    select a.*
    from tablea a
    left join tableb b on b.id = a.id
    where b.id is null or b.datestop > a.date
    

    这个短语为:获取tablea中的所有记录,这些记录要么在tableb中没有与id相同的记录,要么其date小于@中对应记录的datestop 987654327@.

    【讨论】:

      【解决方案3】:

      这是all 可以提供帮助的情况:

      select a.*
      from a
      where a.date < all (select b.datestop
                          from b
                          where b.id = a.id and b.status = 'Stopped'
                         );
      

      【讨论】:

        猜你喜欢
        • 2017-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多