sql - 通过选择最小差异加入多个列并在其中一个整数列中加入
问题描述
我得到了表 t1,我想在下面的 a、b 和 c 列上加入表 t2
+---------+---------+---------+
|a |b |c |
+---------+---------+---------+
|473200 |1 |1.-1-1 |
|472400 |10 |1.-1-1 |
|472800 |10 |1.-1-1 |
|473200 |93 |1.-1-1 |
|472800 |26240 |1.-1-1 |
+---------+---------+---------+
t2
+---------+---------+---------+
|a |b |c |
+---------+---------+---------+
|473200 |1 |1.-1-1 |
|472400 |10 |1.-1-1 |
|472800 |10 |1.-1-1 |
|473200 |93 |1.-1-1 |
|472800 |26250 |1.-1-1 |
+---------+---------+---------+
当我只加入 a 和 c 结果是
+---------+---------+---------+---------+
|t1.b |t2.b |a |c |
+---------+---------+---------+---------+
|93 |1 |473200 |1.-1-1 |
|1 |1 |473200 |1.-1-1 |
|10 |10 |472400 |1.-1-1 |
|10 |10 |472800 |1.-1-1 |
|26240 |10 |472800 |1.-1-1 |
|93 |93 |473200 |1.-1-1 |
|1 |93 |473200 |1.-1-1 |
|10 |26250 |472800 |1.-1-1 |
|26240 |26250 |472800 |1.-1-1 |
+---------+---------+---------+---------+
我试图实现的是将 b 列添加到“on”子句中,以便连接发生在 b 列的最小差异上。
期望的结果
+---------+---------+---------+---------+
|t1.b |t2.b |a |c |
+---------+---------+---------+---------+
|1 |1 |473200 |1.-1-1 |
|10 |10 |472400 |1.-1-1 |
|10 |10 |472800 |1.-1-1 |
|93 |93 |473200 |1.-1-1 |
|26240 |26250 |472800 |1.-1-1 |
+---------+---------+---------+---------+
我在这里看到了类似的东西
https://dba.stackexchange.com/questions/73804/how-to-retrieve-closest-value-based-on-look-up-table
但不知道如何申请我的案子。
解决方案
一种选择是横向连接:
select t1.*, t2.b b2
from t1
cross join lateral (
select t2.*
from t2
where t2.a = t1.a and t2.c = t1.c
order by abs(t2.b - t1.b)
limit 1
)
另一种可能性是distinct on
- 但您需要t1
. 假设(a, c)
元组唯一标识 中的每一行t1
,你会去:
select distinct on (t1.a, t1.c) t1.*, t2.b b2
from t1
inner join t2 on t2.a = t1.a and t2.c = t1.c
order by t1.a, t1.c, abs(t2.b - t1.b)
推荐阅读
- java - 如何指定 T 实现 Comparable
? - reactjs - 使用过滤器方法反应组件错误消息
- node.js - Multer 错误地解析 formData
- java - 如何在 JPA 或 Hibernate 中查询由 @CreatedDate 或 @LastModifiedDate 注释的 LocalDateTime 列?
- javascript - 如何从响应(节点获取)中获取请求对象?
- python - 使用自定义 og:tags 生成自定义链接以在linkedin帖子上共享
- keras - Keras 在构建之后调用之前访问父层的 output_shape
- javascript - 如何使用 JavaScript 在屏幕上移动两辆车
- mysql - 如何将一个mysql查询的结果传递给另一个mysql查询?
- flutter - 在颤动的底部导航栏中使用提供程序调用页面