Why does added RAND() cause MySQL to overload?

孤人 提交于 2019-12-09 04:04:26
OMG Ponies

Using RAND() for ORDER BY is not a good idea, because it does not scale as the data increases. You can see more information on it, including two alternatives you can adapt, in my answer to this question.

Here's a blog post that explains the issue quite well, and workarounds:

http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

And here's a similar warning against ORDER BY RAND() for MySQL, I think the cause is basically the same there:

http://www.webtrenches.com/post.cfm/avoid-rand-in-mysql

Depending on the number of products in your site, that function call is going to execute once per record, potentially slowing the query down.. considerably.

The Too Many Connections error is probably due to this query blocking others while it tries to compute those numbers.

Find another way. ;)

Instead, you can generate random numbers on the programming language you're using, instead of the MySQL side, as rand() is being called for each row

If you know how many records you have you can select a random record like this (this is Perl):

$handle->Sql("SELECT COUNT(0) AS nor FROM table");
$handle->FetchRow();
$nor = $handle->Data('nor');
$rand = int(rand()*$nor)+1;
$handle->Sql("SELECT * FROM table LIMIT $rand,1");
$handle->FetchRow();
.
.
.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!