1

I have a large mysql table with about 25000 rows. There are 5 table fields: ID, NAME, SCORE, AGE,SEX

I need to select random 5 MALES order BY SCORE DESC

For instance, if there are 100 men that score 60 each and another 100 that score 45 each, the script should return random 5 from the first 200 men from the list of 25000

ORDER BY RAND()

is very slow

The real issue is that the 5 men should be a random selection within the first 200 records. Thanks for the help

Enstine Muki
  • 421
  • 1
  • 4
  • 8

2 Answers2

2

I dont think that sorting by random can be "optimised out" in any way as sorting is N*log(N) operation. Sorting is avoided by query analyzer by using indexes.

The ORDER BY RAND() operation actually re-queries each row of your table, assigns a random number ID and then delivers the results. This takes a large amount of processing time for table of more than 500 rows. And since your table is containing approx 25000 rows then it will definitely take a good amount of time.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

so to get something like this I would use a subquery.. that way you are only putting the RAND() on the outer query which will be much less taxing.

From what I understood from your question you want 200 males from the table with the highest score... so that would be something like this:

SELECT * 
FROM table_name
WHERE age = 'male'
ORDER BY score DESC
LIMIT 200

now to randomize 5 results it would be something like this.

SELECT id, score, name, age, sex
FROM
(   SELECT * 
    FROM table_name
    WHERE age = 'male'
    ORDER BY score DESC
    LIMIT 200
) t -- could also be written `AS t` or anything else you would call it
ORDER BY RAND()
LIMIT 5
John Ruddell
  • 25,283
  • 6
  • 57
  • 86