简体   繁体   English

MYSQL:rand()的查询顺序非常慢

[英]MYSQL: Query order by rand() very slow

I have to pick 30 random records from a table, except that the query uses one second, and this slows mysql if the content is displayed by many users. 我必须从表中选择30个随机记录,除了查询使用一秒钟,如果许多用户显示内容,这会减慢mysql的速度。 This is the query: 这是查询:

SELECT relationship, COUNT(id) AS number FROM FR_user_friends GROUP BY relationship ORDER BY rand() LIMIT 30

Do you know how to speed up this query? 你知道如何加快这个查询吗? Thank you. 谢谢。

If I remove rand() the query is fast. 如果我删除rand(),查询速度很快。 We have to find an alternative for rand() 我们必须找到rand()的替代方案

ORDER BY RAND() causes the engine to generate random values for all rows, so if you want to select a few rows from a large table, it gives very bad performance. ORDER BY RAND()使引擎为所有行生成随机值,因此如果要从大表中选择几行,则会产生非常糟糕的性能。

You could for example generate 30 random values in php in the range [1, maximum row-id] and select the first row with a row-id that is bigger or equal to the random value with LIMIT 1 . 例如,您可以在[1,最大行ID]范围内的php中生成30个随机值,并选择第一行的行ID大于或等于LIMIT 1的随机值。

SQL-only ways to deal with this you find in How can i optimize MySQL's ORDER BY RAND() function? 您可以在如何优化MySQL的ORDER BY RAND()函数中找到只处理SQL的方法吗? (but some are not trivial as well). (但有些也不是微不足道的)。

the RAND() function is too slow and consumes too much CPU. RAND()函数太慢并且消耗太多CPU。 it generates a random number for every row and picks the smallest one so that's why it's so slow. 它为每一行生成一个随机数,并选择最小的一个,这就是为什么它如此慢。

For speed up you can generate a random number in PHP and use in LIMIT clause like this: 为了加快速度,您可以在PHP中生成一个随机数,并在LIMIT子句中使用,如下所示:

$firstClauseLimit = rand(0,20); // create an int random number between 0 to 20

"... ... LIMIT $firstClauseLimit,1"

by this way, it will be so faster. 通过这种方式,它会更快。

This query should be much faster than your 此查询应该比您的查询快得多

SELECT relationship, id 
FROM FR_user_friends fr1 
JOIN (
  SELECT CEIL(RAND() * ( SELECT MAX(id) FROM FR_user_friends )) AS id ) AS fr2 
  ON fr1.id >= fr2.id 
  LIMIT 0,30

I also suggest read more here: What would be faster? 我还建议在这里阅读更多内容: 什么会更快?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM