Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get another order after limit

Imagine I've a table 'users' with two fields: 'age' and 'name'. I want to retrieve the top ten older users and then I want this list of ten sorted by name.

Is it possible to do it with MySQL?

I've tried this: (doesn't work)

SELECT * FROM users order by age, name limit 10
like image 388
ana Avatar asked Oct 16 '11 19:10

ana


1 Answers

Use a subselect:

SELECT * FROM
(
    SELECT *
    FROM users
    ORDER BY age DESC
    LIMIT 10
) AS T1
ORDER BY name

The inner select finds the 10 rows you want to return, and the outer select puts them in the correct order.

like image 107
Mark Byers Avatar answered Oct 14 '22 11:10

Mark Byers