且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何优化缓慢的MySQL查询由于ORDER BY RAND()?

更新时间:2023-01-12 15:37:05

你只选择一行,我想你可以选择一个随机由LIMIT随机排列。示例:

You are choosing only one row , I think you can choose one row randomly by LIMIT randomly. Example:

如果您有:

SELECT * table  ORDER BY RAND( )  LIMIT 1;

更改为

SELECT * table    LIMIT $randomvalue  ,$randomvalue + 1;

$ randomvalue是从应用程序级别选择的随机值。

$randomvalue is a random value chosen from the application level.

更新:以下答案比上述更清楚。

update: the following answer is more clear than the above one.

//get the total number of rows
$result= mysql_query(" SELECT  COUNT(*) AS total FROM `table` ");
$row = mysql_fetch_array($result);
$total=$row['total'];


//create random value from 1 to the total of rows 
$randomvalue =rand(1,$total);


//get the random row

$result= mysql_query(" SELECT  * FROM `table` limit $randomvalue,1");