我有两张桌子:

连接器_状态

连接器 status_timestamp status
1 2020-03-03 09:07:09.058000 available
2 2020-03-03 09:51:03.852000 faulted
1 2022-10-06 16:32:14.130000 charging
3 2022-10-06 16:28:26.228000 available
4 2022-10-06 16:28:03.195000 charging

连接器

连接器 box_id 连接器_id
1 Alpha 0
2 Alpha 1
3 Beta 0
4 Beta 1

My 连接器_状态 table has multiple rows for each 连接器, but I only want the most recent row, based on the box_id

I would like to join the tables based on box_id but using the latest timestamp from the 2x 连接器s. This would select status charging based on the above table

连接表看起来有点像这样:

连接器 status_timestamp status box_id
1 2020-03-03 09:07:09.058000 available Alpha
2 2020-03-03 09:51:03.852000 faulted Alpha
1 2022-10-06 16:32:14.130000 charging Alpha
3 2022-10-06 16:28:26.228000 available Beta
4 2022-10-06 16:28:03.195000 charging Beta

获得预期的结果:

box_id status
Alpha Charging
Beta Available

我有以下代码

SELECT IF(连接器_状态.status = 'Charging','Charging', IF(连接器_状态.status ='Available','Not Occupied', IF(连接器_状态.status = 'Faulted','Faulted','Occupied'))) AS group_status, 连接器.连接器_id, 连接器.box_id, status_timestamp FROM 连接器_状态 JOIN 连接器 ON 连接器_状态.连接器 = 连接器.连接器 GROUP BY 连接器.box_id ORDER BY 连接器.box_id

不过,我不知道如何对box_id执行联接以获得最大时间戳.

What is confusing me is if i firstly get the latest timestamp from the 连接器_状态 table and then try and join by box_id, how can i be sure that it will take the latest 连接器 timestanmp for that box_id

推荐答案

您可以使用ROW_NUMBER获得所需的结果:

select box_id,
       status       
from (   select status,
                box_id,
                row_number() over( partition by tbl.box_id order by tbl.status_timestamp desc ) as rn
         from   (  select   status_timestamp,
                            status,
                            box_id
                   from connector_status cs
                   inner join connector c on c.connector=cs.connector 
                ) as tbl
     ) as x where rn=1 ;

https://dbfiddle.uk/1LRcbbma

Mysql相关问答推荐

SQL按另一个表中的字段进入顺序对子查询进行排序

mysql查询汇总数据

为什么我的带有索引字段和非索引字段的 Select 有时需要很长时间

从MySQL JSON列中检索数组中的所有答案

在MySQL的join查询中进行计算

使用sql查找源和最终目的地

有没有比使用 MySQL 计划事件更好的方法来更新我的数据库表中的列?

使用 Having 表达式连接多个表

如何在更新语句中使用多个子字符串函数?

如何解决这个特定的 SQL 查询?我的解决方案还返回不想要的值

如何在任何连续范围内获得最大值

MySQL REGEXP 在没有 BINARY 模式的情况下区分大小写?

如何在 SQL 的计算列中显示小数点后两位?

MySQL:低基数/ Select 性列=如何索引?

Ansible 幂等 MySQL 安装 Playbook

如何在 MySQL 上一次删除一系列记录?

MySQL Workbench 无法加载 mysql.proc

在 MySQL 中删除数据库返回删除数据库错误:66

MySQL错误 1005 (HY000): 无法创建表 'foo.#sql-12c_4' (errno: 150)

mysql GROUP_CONCAT 重复