首页 > 解决方案 > 如何连接数据表以选择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

我会非常感谢任何帮助,谢谢

标签: phpsql

解决方案


您的错误消息是因为您的 td 子查询没有 device_id。您可以通过更改为 来添加SELECT Location FROM devicesSELECT 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如果您希望在按日期打成平手时只获得一条记录,则可以使用。


推荐阅读