tags:

views:

53

answers:

2

I'm using full text search to pull rows.
I order the rows based on score (ORDER BY SCORE) , then of the top 20 rows (LIMIT 20), I want to rand (RAND) the result set.

So for any specific search term, I want to randomly show 5 of the top 20 results.

My workaround is code based- where I put the top 20 into an array then randomly select 5.

Is there sql way to do this?

+3  A: 

You can do this using an inner select. Select the top twenty rows in the inner select. In the outer select order these rows randomly and select the top five:

SELECT *
FROM (
    SELECT *
    FROM table1
    ORDER BY score DESC
    LIMIT 20
) AS T1
ORDER BY RAND()
LIMIT 5
Mark Byers
Does RAND evaluate differently for each row in MySQL? (I ask because in SQL Server you'd have to use NEWID)
gbn
+1 The other workaround is a double nested query (@gbn: yes it does)
Andomar
@gbn: `ORDER BY RAND() combined with LIMIT is useful for selecting a random sample from a set of rows` from http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand
Mark Byers
Ordering only 20 rows without a key probably won't be noticeable to the user, plus you're not sending the unused rows to the client.
Marcus Adams
If there are 21 people with the same high score, it's possible that the 21st person never gets displayed. Removing the inner LIMIT would be more fair, but it would cost you performance wise. Just something to think about. You could tell them that in order to be guaranteed a place on the wall, they need to **beat** the high score.
Marcus Adams
A: 

For a code based solution, using arrays, try the modern Fisher-Yates Shuffle.

Marcus Adams