[英]Get last record of each ID
I have this query:我有这个查询:
SELECT Truck.Name AS name,
timestamp,
oil,
diesel,
cargo,
Truck.notes AS Remarks
FROM trip
INNER JOIN Truck USING (idTruck)
WHERE idTruck IN('2','4','5','6','7','8','9','11','12','13','14','15','16')
ORDER BY name, timestamp DESC
which returns ALL records from the ID's I was thinking of using CURDATE as它从我正在考虑使用 CURDATE 的 ID 返回所有记录
AND DATE(timestamp) = CURDATE()
in order to get last records but when a record is not modified a day (they usually do but sometimes this is not the case) I'm loosing the records.为了获得最后的记录,但是当一天没有修改记录时(他们通常会这样做,但有时情况并非如此)我正在丢失记录。 How would I modify the query to get the last entry of each idTruck regardless of the timestamp in a single query?
无论单个查询中的时间戳如何,我将如何修改查询以获取每个 idTruck 的最后一个条目?
I suggest you use the MAX function of sql to get the last record ( MAX(Truck.Name) ):我建议您使用 sql 的 MAX function 来获取最后一条记录( MAX(Truck.Name) ):
SELECT MAX(Truck.Name) AS name,
timestamp,
oil,
diesel,
cargo,
Truck.notes AS Remarks
FROM trip
INNER JOIN Truck USING (idTruck)
WHERE idTruck IN('2','4','5','6','7','8','9','11','12','13','14','15','16')
ORDER BY name, timestamp DESC
To get the last record of each ID:获取每个 ID 的最后一条记录:
SELECT MAX(Truck.Name) AS name,
timestamp,
oil,
diesel,
cargo,
Truck.notes AS Remarks
FROM trip
INNER JOIN Truck USING (idTruck)
WHERE idTruck IN('2','4','5','6','7','8','9','11','12','13','14','15','16')
GROUP BY idTruck
ORDER BY name, timestamp DESC
because according to sql.sh( https://sql.sh/fonctions/agregation/max ):因为根据 sql.sh( https://sql.sh/fonctions/agregation/max ):
the aggregation function MAX() allows to return the maximum value of a column in a record set.
聚合 function MAX() 允许返回记录集中列的最大值。 The function can be applied to numeric or alphanumeric data.
function 可应用于数字或字母数字数据。 For example, it is possible to search for the most expensive product in a table in an online shop.
例如,可以在网上商店的表格中搜索最昂贵的产品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.