简体   繁体   中英

SQL join greater than / less then

I have 2 tables

第一的

第二

I So i need to get a table in which rows will be excluded for which the date for each "id" is more than in the second table "datestop"

I tried inner join with double condition: id = id and Date < DateStop, but in this way also excluded rows which not contained in table 2 (id1)

For imagine, thats what i want to get:

结果

I would use NOT EXISTS which is very efficient:

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

It's not clear if you need the value of Status must be 'Stopped' for your requirement.
So maybe you need to change the WHERE clause of the subquery to:

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

Consider:

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

This phrases as: get all records in tablea for which either there is no record with the same id in tableb , or whose date is less than the datestop of the corresponding record in tableb .

This is a situation where all can be helpful:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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