繁体   English   中英

SQL join 大于/小于 then

[英]SQL join greater than / less then

我有2张桌子

第一的

第二

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

我尝试使用双重条件进行内部连接:id = id 和 Date < DateStop,但以这种方式也排除了表 2 (id1) 中未包含的行

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

结果

我会使用非常有效的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'

考虑:

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没有具有相同idtableb ,或者其date小于datestop中相应记录的tableb

在这种情况下, all可以提供帮助:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM