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
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 ?
Advertisement
Answer
I suggest you use the MAX function of sql to get the last record (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 :
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):
the aggregation function MAX() allows to return the maximum value of a column in a record set. The function can be applied to numeric or alphanumeric data. For example, it is possible to search for the most expensive product in a table in an online shop.