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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…