SQLite Forum

Nearest-match join
Login
To select all the matching data:

```
create table t1 (id integer primary key, ts not null unique, a, b, c);
create table t2 (id integer primary key, ts not null unique, d, e, f);

select *
  from t1, t2
 where t2.id == (
                 select id2
                   from (
                            select delta,
                                   id2
                              from (
                                      select id as id2,
                                             ts - t1.ts as delta
                                        from t2
                                       where ts >= t1.ts
                                    order by ts
                                       limit 1
                                   )
                         union
                            select delta,
                                   id2
                              from (
                                      select id as id2,
                                             t1.ts - ts as delta
                                        from t2
                                       where ts <= t1.ts
                                    order by ts desc
                                       limit 1
                                   )
                        )
                )
;
```