I want to select a bunch of data from a table using a GROUP BY clause. This works great, but I need to order the data by the date it was created, with an ORDER BY clause. My question is, can I use both these clauses within the same query, or should I be using one in a sub-query, or something else?
The original query (no modification) is this:
SELECT *
FROM table
WHERE tag_draft=0
AND
(
(target_id=2 AND tag_del_target=0)
OR (source_id=2 AND tag_del_source=0)
)
AND updated IN
(
SELECT MAX(updated)
FROM table
GROUP BY thread_id
)
ORDER BY updated DESC
Hopefully this question is readable enough to be able to answer it.
The MySQL SELECT syntax is:
So yes, you can use GROUP BY and ORDER BY in the same query. What won’t order the results properly is to use ORDER BY in a sub-query. For example:
It doesn’t make any sense first to order the sub-query, then to make join.