【发布时间】:2020-05-20 12:14:58
【问题描述】:
这是一个表vehicle_connection_status,其中包含如下所示的数据:
+------------+-------------+---------------+-------------+--------------+
| "idStatus" | "vehicleId" | "isConnected" | "missionId" | "lastUpdate" |
+------------+-------------+---------------+-------------+--------------+
| "8" | "1" | "0" | "1" | "10" |
| "9" | "1" | "1" | "1" | "9" |
| "10" | "2" | "0" | "1" | "9" |
| "11" | "2" | "1" | "1" | "8" |
| "12" | "3" | "1" | "1" | "11" |
| "13" | "4" | "0" | "1" | "9" |
| "14" | "4" | "1" | "1" | "10" |
| "15" | "4" | "0" | "1" | "11" |
+------------+-------------+---------------+-------------+--------------+
如果我运行查询
select vehicleId, isConnected, max(lastUpdate) lasts
from vehicle_connection_status
where missionId =1
group by vehicleId, isConnected
我会得到如下结果:
+-------------+---------------+---------+
| "vehicleId" | "isConnected" | "lasts" |
+-------------+---------------+---------+
| "1" | "0" | "10" |
| "1" | "1" | "9" |
| "2" | "0" | "9" |
| "2" | "1" | "8" |
| "3" | "1" | "11" |
| "4" | "0" | "11" |
| "4" | "1" | "10" |
+-------------+---------------+---------+
我想要的是每个“vehicleId”具有最高“lasts”但具有“isConnected”和“vehicleId”字段的文件,我正在寻找的结果是:
+-------------+---------------+---------+
| "vehicleId" | "isConnected" | "lasts" |
+-------------+---------------+---------+
| "1" | "0" | "10" |
| "2" | "0" | "9" |
| "3" | "1" | "11" |
| "4" | "0" | "11" |
+-------------+---------------+---------+
基本上把“isconected”加到
select vehicleId, max(lastUpdate) lasts
from vehicle_connection_status where missionId =1 group by vehicleId
+-------------+---------+
| "vehicleId" | "lasts" |
+-------------+---------+
| "1" | "10" |
| "2" | "9" |
| "3" | "11" |
| "4" | "11" |
+-------------+---------+
我看过其他类似的问题:
Retrieving the last record in each group - MySQL
但我无法解决问题。
问题是我不知道如何在需要时避免按 isconnected 分组。
我收到以下错误:
/* Error de SQL (1055): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'x.idStatus' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by */
我尝试过其他方法:
区别:
SELECT DISTINCT
vehicleId,
isconnected,
lastUpdate
FROM vehicle_connection_status t1
WHERE lastUpdate in (SELECT
MAX(t2.lastUpdate)
FROM vehicle_connection_status t2
GROUP BY vehicleId)
还有其他更深奥的,
select v1.vehicleId, v1.isConnected , v1.lastUpdate
from vehicle_connection_status v1
inner join
(select v2.vehicleId, v2.isConnected , max(v2.lastUpdate) as latest
from vehicle_connection_status v2 group by v2.vehicleId, v2.isConnected) vc
on vc.vehicleId = v1.vehicleId and vc.latest = v1.lastUpdate
where v1.missionId =1
但不起作用。
目前,我使用第一个查询以编程方式解析结果集来获取所需的结果,但这不是最佳解决方案。
测试:
【问题讨论】: