ORDER BY Subquery for GROUP BY to JOIN conversion
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 BY
in the subquery is useless):
SELECT *
FROM table
GROUP BY title
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:
SELECT t.*
FROM
table AS t
JOIN
( SELECT title
, MAX(timestamp) AS maxts
FROM table
GROUP BY title
) AS grp
ON grp.title = t.title
AND grp.maxts = t.timestamp
ORDER BY t.timestamp DESC
For the record, your original query:
SELECT *
FROM
( SELECT *
FROM table
ORDER BY timestamp DESC
) m
GROUP BY title
might work as expected, but: only in MySQL that allows you to use in the SELECT
list fields that are not in the GROUP BY
clause (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 by timestamp 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 BY
queries.
The sql statement is invalid.
ORDER BY is invalid in an subquery
GROUP BY needs an aggregate function, like COUNT, SUM etc.
SELECT COUNT(*) FROM table
GROUP BY title
ORDER BY title
精彩评论