tags:

views:

24

answers:

1

I am trying to find a way to pull 10 random records and then order those 10 records by a field. I have tried the following:

SELECT name FROM users ORDER BY RAND(), name LIMIT 10

but it does not order by name with 10 rows returned, just return 10 random record in any order. Is there a way to order by rand() and a field within a query with MySQL?

+5  A: 
SELECT  name
FROM    (
        SELECT  name
        FROM    users
        ORDER BY
                RAND()
        LIMIT 10
        ) q
ORDER BY
        name
Quassnoi
I was hoping for a solution not involving subqueries as implementing subqueries would be difficult
ryanzec
@ryanzec: what's difficult in a subquery?
Quassnoi
Well the query is being created through a complex process using a bunch of different form values and is also being decoded in order to generate the values for the form fields. Not saying it can't be done but I would would have to figure how to get the query generated properly (I am not the one who create this query generation process in the first place) and then make sure it does not break the decoding of the query (which using a bunch of regular expressions). Just hoping for a solution that would be less than a day (might end up doing the random sort in MySQL and the field sort in PHP)
ryanzec
@ryanzec: with only `10` values, it may be better indeed to sort it on `PHP` side.
Quassnoi