I need to retrieve rows from a table (i.e: 'orders') ordered by a column (lets say 'user') randomly. That is, I need all orders from the same user to remain together (one after the other) and users to be ordered randomly.
A:
How random does it have to be? I can think of a few possible answers.
If the "random" sequence should be repeatable, you can sort by a hash of the user ID, using MD5 or a custom one you create yourself e.g. ORDER BY MD5(), secondary_sort_column.
Matt Kane
2009-03-12 14:44:42
+3
A:
I'm going to assume you have a second table called "users" that has all the users in it. If not, you could still do this by adding another SELECT DISTINCT subquery on orders, but that would be much messier:
SELECT orders.*
FROM orders
INNER JOIN (SELECT userid, RAND() as random FROM users) tmp
ON orders.userid = tmp.userid
ORDER BY tmp.random, tmp.userid
You'll want to order by the random number AND the user id so if two user ids get the same random number their orders won't be all jumbled together.
Eric Petroelje
2009-03-12 14:45:12
Exactly what I was looking for. Many Thanks!
Gerardo
2009-03-12 14:59:27
This doesn't work in MS SQL Server. RAND() will evaluate to a constant and give every user_id the same value for 'random'...
Dems
2009-03-12 18:59:02
Good thing he's using MySQL then :)
Eric Petroelje
2009-03-12 19:03:34