How to group by DESC order
Normally MySQL allows group by ascending order records only. So we can order records before grouping.
SELECT * FROM ( SELECT * FROM questions ORDER BY id DESC ) AS questions GROUP BY questions.asker
The records need to be grouped using GROUP BY
and MAX()
to get the maximum ID for every asker
.
SELECT asker, MAX(ID) ID
FROM TableName
GROUP BY asker
- SQLFiddle Demo
OUTPUT
╔════════╦════╗
║ ASKER ║ ID ║
╠════════╬════╣
║ Bob ║ 2 ║
║ Marley ║ 3 ║
╚════════╩════╝
If you want the last id
for each asker
, then you should use an aggregate function:
SELECT max(id) as id,
asker
FROM questions
GROUP by asker
ORDER by id DESC
The reason why you were getting the unusual result is because MySQL uses an extension to GROUP BY
which allows items in a select list to be nonaggregated and not included in the GROUP BY clause. This however can lead to unexpected results because MySQL can choose the values that are returned. (See MySQL Extensions to GROUP BY)
From the MySQL Docs:
MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. ... You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values the server chooses.
Now if you had other columns that you need to return from the table, but don't want to add them to the GROUP BY
due to the inconsistent results that you could get, then you could use a subquery to do so. (Demo)
select
q.Id,
q.asker,
q.other -- add other columns here
from questions q
inner join
(
-- get your values from the group by
SELECT max(id) as id,
asker
FROM questions
GROUP by asker
) m
on q.id = m.id
order by q.id desc