且构网

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

MYSQL:通过 rand() 查询订单非常慢

更新时间:2023-09-14 21:23:28

ORDER BY 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.

例如,您可以在 php 中生成 30 个范围 [1, 最大行 ID] 的随机值,然后选择行 ID 大于或等于 LIMIT 1.

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.

我如何优化 MySQL 的 ORDER BY RAND() 函数?(但有些也不是微不足道的).

SQL-only ways to deal with this you find in How can i optimize MySQL's ORDER BY RAND() function? (but some are not trivial as well).