i have this table
id | title | amount | timestamp
1 | random1 | 150 | 1313635011
2 | random2 | 190 | 1313635730
3 | random2 | 210 | 1313637359
4 | random2 | 100 | 1313691807
5 | random3 | 130 | 1313692673
6 | random4 | 900 | 1313692739
7 | random4 | 111 | 1313692988
i want to get this result (rows with different titles and biggest timestamps):
id | title | amount | timestamp
1 | random1 | 150 | 1313635011
4 | random2 | 100 | 1313691807
5 | random3 | 130 | 1313692673
7 | random4 | 111 | 1313692988
i have this query.
SELECT * FROM (
SELECT * FROM table ORDER BY timestamp DESC
) m GROUP BY title
It works as charm but can this be converted to a JOIN statement?
Thanks
This can be simplified to the following (the
ORDER BYin the subquery is useless):Why do you think that you need
JOIN? (Ok, this was resolved by comments).After your comment that you need for every title, the row with biggest timestamp, this would do the work:
For the record, your original query:
might work as expected, but: only in MySQL that allows you to use in the
SELECTlist fields that are not in theGROUP BYclause (or depend on those), without any aggregate functions in them. So, the above query will return a more or less random row for every title. In fact, it will return the first row it will find for a title. So, having first run the subquery (which orders bytimestamp DESC) results in finding first the row with biggest timestamp.This however, only happens because (when, if) the optimizer does not understand that the subquery is useless. You may find that your original query runs fine when one day you upgrade to MySQL version 7.5 and your query stops working as before. (because the optimizer got more clever and translated your query to a simpler without sub-select).
You may even find your query to stop working altogether and produce error if MySQL decides in a future release to be in terms with SQL standards for the
GROUP BYqueries.