I would like to take a database of say, 1000 users and select 20 random ones (ORDER BY rand()
,LIMIT 20
) then order the resulting set by the names. I came up with the following query which is not working like I hoped.
SELECT * FROM users WHERE 1 ORDER BY rand(), name ASC LIMIT 20
Use a subquery:
or a join to itself:
Instead of using a subquery, you could use two separate queries, one to get the number of rows and the other to select the random rows.
Then, get a random twenty rows.
The final query:
Beware of ORDER BY RAND() because of performance and results. Check this article out: http://jan.kneschke.de/projects/mysql/order-by-rand/
Use a subquery:
The inner query selects 20 users at random and the outer query orders the selected users by name.