MySQL RAND() 排序优化
ORDER BY RAND() 的缓慢查询带来了性能挑战。
问题
ORDER 查询BY RAND() 通常会导致性能不佳,特别是在大型或频繁更新的表上。 MySQL 的解决方案(MySQLPerformanceBlog)可能不够。
解决方案
要优化 RAND() 排序,请考虑以下方法:
SELECT * FROM ( SELECT @cnt := COUNT(*) + 1, @lim := 10 FROM t_random ) vars STRAIGHT_JOIN ( SELECT r.*, @lim := @lim - 1 FROM t_random r WHERE (@cnt := @cnt - 1) AND RAND(20090301) < @lim / @cnt ) i
这种方法通过在迭代数据时保持运行概率来避免排序,使其比 ORDER BY 更高效RAND().
对于单行选择
要选择单个随机行,请尝试以下查询:
SELECT aco.* FROM ( SELECT minid + FLOOR((maxid - minid) * RAND()) AS randid FROM ( SELECT MAX(ac_id) AS maxid, MIN(ac_id) AS minid FROM accomodation ) q ) q2 JOIN accomodation aco ON aco.ac_id = COALESCE ( ( SELECT accomodation.ac_id FROM accomodation WHERE ac_id > randid AND ac_status != 'draft' AND ac_images != 'b:0;' AND NOT EXISTS ( SELECT NULL FROM accomodation_category WHERE acat_id = ac_category AND acat_slug = 'vendeglatohely' ) ORDER BY ac_id LIMIT 1 ), ( SELECT accomodation.ac_id FROM accomodation WHERE ac_status != 'draft' AND ac_images != 'b:0;' AND NOT EXISTS ( SELECT NULL FROM accomodation_category WHERE acat_id = ac_category AND acat_slug = 'vendeglatohely' ) ORDER BY ac_id LIMIT 1 ) )
此优化假设ac_ids 分布比较均匀。
以上是如何使用 ORDER BY RAND() 优化 MySQL 查询?的详细内容。更多信息请关注PHP中文网其他相关文章!