How can i optimize MySQL's ORDER BY RAND() function?

前端 未结 8 2274
天命终不由人
天命终不由人 2020-11-22 00:58

I\'d like to optimize my queries so I look into mysql-slow.log.

Most of my slow queries contains ORDER BY RAND(). I cannot find a real solu

8条回答
  •  情深已故
    2020-11-22 01:29

    It depends on how random you need to be. The solution you linked works pretty well IMO. Unless you have large gaps in the ID field, it's still pretty random.

    However, you should be able to do it in one query using this (for selecting a single value):

    SELECT [fields] FROM [table] WHERE id >= FLOOR(RAND()*MAX(id)) LIMIT 1
    

    Other solutions:

    • Add a permanent float field called random to the table and fill it with random numbers. You can then generate a random number in PHP and do "SELECT ... WHERE rnd > $random"
    • Grab the entire list of IDs and cache them in a text file. Read the file and pick a random ID from it.
    • Cache the results of the query as HTML and keep it for a few hours.

提交回复
热议问题