How can I select rows with most recent timestamp for each key value?

For the sake of completeness, here’s another possible solution: SELECT sensorID,timestamp,sensorField1,sensorField2 FROM sensorTable s1 WHERE timestamp = (SELECT MAX(timestamp) FROM sensorTable s2 WHERE s1.sensorID = s2.sensorID) ORDER BY sensorID, timestamp; Pretty self-explaining I think, but here’s more info if you wish, as well as other examples. It’s from the MySQL manual, but above query works … Read more

Mysql select distinct

DISTINCT is not a function that applies only to some columns. It’s a query modifier that applies to all columns in the select-list. That is, DISTINCT reduces rows only if all columns are identical to the columns of another row. DISTINCT must follow immediately after SELECT (along with other query modifiers, like SQL_CALC_FOUND_ROWS). Then following … Read more

How to select the most recent set of dated records from a mysql table

This solution was updated recently. Comments below may be outdated This can query may perform well, because there are no joins. SELECT * FROM ( SELECT *,if(@last_method=method,0,1) as new_method_group,@last_method:=method FROM rpc_responses ORDER BY method,timestamp DESC ) as t1 WHERE new_method_group=1; Given that you want one resulting row per method this solution should work, using mysql … Read more

Get most recent row for given ID

Use the aggregate MAX(signin) grouped by id. This will list the most recent signin for each id. SELECT id, MAX(signin) AS most_recent_signin FROM tbl GROUP BY id To get the whole single record, perform an INNER JOIN against a subquery which returns only the MAX(signin) per id. SELECT tbl.id, signin, signout FROM tbl INNER JOIN … Read more