php - 如何连接数据表以选择sql中的最新记录
问题描述
我有两个单独的表 LPG_usage 和设备。在 LPG_usage 表中有 5 列(Device_id,Cylinder_Type,Date,Kg,Data_index),设备表有 3 列(Device_id,User_name,Location)
我想通过考虑 LPG_usage 表中所有 Device_id 的日期以及设备表中的位置来选择最新记录。选中的表包括(Device_id,Cylinder_Type,Date,Kg,Location)
我对此进行了查询,但它在“on 子句”中作为未知列“td.Device_id”出现错误,我的代码如下
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
INNER JOIN (
SELECT Location FROM devices
)td on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate and t.Device_id = td.Device_id
我会非常感谢任何帮助,谢谢
解决方案
您的错误消息是因为您的 td 子查询没有 device_id。您可以通过更改为 来添加SELECT Location FROM devices
它SELECT device_id, Location FROM devices
。您还需要将on
连接到 td 中的一些条件移动到on
连接到 tm 的新条件。
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate
INNER JOIN (
SELECT device_id, Location FROM devices
)td
on t.Device_id = td.Device_id
以上应该可以工作,但我不清楚为什么你有 td 的子查询。我建议考虑:
select t.Device_id, t.Date, t.Kg,t.Cylinder_Type,td.Location
from lpg_usage t
inner join (
select Device_id, max(Date) as Last_upDate
from lpg_usage
group by Device_id
) tm
on t.Device_id = tm.Device_id and t.Date = tm.Last_upDate
INNER JOIN devices td
on t.Device_id = td.Device_id
在现代数据库上要考虑的另一种选择是:
SELECT device_id, data, kg, cylinder_type, location
FROM
(
select t.Device_id, t.Date, t.Kg, t.Cylinder_Type, td.Location, RANK() OVER(PARTITION BY t.device_id ORDER BY t.data DESC) rk
from lpg_usage t INNER JOIN devices td
on t.Device_id = td.Device_id
)
WHERE rk = 1
内部查询使用窗口函数 ( RANK
) 以给定顺序 ( t.date DESC
) 对每个 device_id 的结果进行编号。外部查询使用它来仅获取每个 device_id 的最大日期。这使用RANK
它会返回多行的关系(如您的原始查询)。ROW_NUMBER
如果您希望在按日期打成平手时只获得一条记录,则可以使用。
推荐阅读
- python - Tensorflow v1.14 中的内核约束使用
- c# - 如何在 OpenGL 中直接使用屏幕空间坐标?
- kotlin - 安全控制器的测试
- node.js - 关于异步中复杂的商业逻辑
- javascript - 在 reactjs 中使用按钮创建显示和隐藏部分
- java - 如何找出从起点到终点经纬度的持续时间?
- android - 当我将可触摸之外的弹出窗口设置为错误时,编辑文本不会在弹出窗口中显示键盘
- ffmpeg - 将多个图像组合成一条图像 ffmpeg
- flexbox - 一个 flexbox 容器中的两个饼图
- apache-calcite - 如何将 Calcite 逻辑计划转换为另一个数据引擎的物理计划?