I have a table without IDs. it has 3 columns: the name of a computer, its status (on/off) at the moment of the poll, and the timestamp of the insertion.
if I run
select * from computers group by name;
I get a line for each computer (there are 200 different ones), but these lines don’t always hold the latest entry for it.
I then tried
select computers group by name order by timestamp asc;
But I get incoherent responses (some recent timestamps, some old ones… no idea why).
It’s basically the same problem as here : SQL: GROUP BY records and then get last record from each group?, but I don’t have ids to help 🙁
You can write:
The above uses this subquery to finds the greatest
timestampfor eachname:and then it gathers fields from
computerswhosenameandtimestampmatch something that the subquery returned.The reason that your
order byclause has no effect is that it comes too “late”: it’s used to order records that are going to be returned, after it’s already determined that they will be returned. To quote from §11.16.3 “GROUP BYandHAVINGwith Hidden Columns” in the MySQL 5.6 Reference Manual on this subject:Another way is to write a correlated subquery, and dispense with the
GROUP BYentirely. This:finds all rows in
computersthat haven’t been superseded by more-recent rows with the samename. The same approach can be done with a join:which is less clear IMHO, but may perform better.