mysql - SQL join a table with exact time or before it
问题描述
I would like to get a results table based on table2 with potential values not found in the table1. For example lets say I have table1 with
time | col1 | col2
10 | a | b
15 | c | d
23 | e | f
45 | g | h
61 | i | j
70 | k | l
and table2 with
time
8
23
55
72
results should be
time | col1 | col2
8 | null | null
23 | e | f
55 | g | h
72 | k | l
One way to look at the example is like a time table. Say a time table of a president or a ruler. So in year/time 10 a b
became the ruler. At year/time 8, there is no ruler so its null. At year/time 55, g h
should still be the ruler.
解决方案
You can use left join
. . . along with lead()
to get the end time:
select t2.*, t1.col1, t1.col2
from table2 t2 left join
(select t1.*, lead(time) over (order by time) as next_time
from table1 t1
) t1
on t2.time >= t1.time and
(t2.time < t1.next_time or t1.next_time is null);
推荐阅读
- docker - 使用 Nginx 的 Docker 容器中的反向代理问题
- static - 在 Flutter 中保留所有常量的最佳做法是什么?
- google-chrome-extension - 为什么 MakeAppx 生成 0 kb 文件?
- java - 试图将此活动转换为android studio中的片段,到目前为止还没有运气
- julia - 如何使用具有不同成员的集合作为索引?
- ruby-on-rails - 发生 Chage Rails 版本冲突后,Bundler 找不到 gem 的兼容版本
- javascript - useState 设置方法不会立即反映更改
- android - 如何以编程方式更新 Android 中的联系人图像?
- cheerio - 如何使用 Cheerio 获取 html 的所有元素内容?
- php - 如何在 Wordpress 主题页面上集成 SteveMorse.org PHP 数据库