tags:

views:

36

answers:

2

My query selects results correctly using ORDER BY CASE. I would like to randomize the results within EACH case. i.e. ORDER BY CASE WHEN apples (randomize) THEN 1 WHEN pears (randomize) THEN 2, etc. So my results are still ordered by each case but within the results PER case they are random, each time the query is run.

A: 

You can try ORDER BY CASE, RAND(). RAND() generates a random number, of course.

However, I heard somewhere that shuffling elements in SQL is not quite the most efficient way and it is better to randomize elements in PHP. But randomizing them per case is not a trivial task. (PHP rand() function)

phimuemue
I believe there is an issue with using RAND to sort in MySQL when the result set is large, but I am not 100% certain.
Phil Wallach
Yes there is: http://jan.kneschke.de/projects/mysql/order-by-rand/
ircmaxell
this does work however - after the case, 'when', 'then' and END, RAND() - finishes the query off perfectly.
InnateDev
A: 

Often times for simplicity I will throw a NewID() function into a SQL Order By to randomize the order of the results. In your case, you could use the uniqid(), or if you really are passing the query straight to MSSQL, you could use NEWID() as well...

fdfrye
how would this work in MySQL - Im not sure what I should be 'google-ing' here NewID() ??
InnateDev
MySql uses uniqid() to generate the equivalent of a GUID. Give that a try...
fdfrye