ORDER BY RAND() 函数需要很长时间才能在 mysql 中执行 [英] ORDER BY RAND() function taking long time to execute in mysql

查看:47
本文介绍了ORDER BY RAND() 函数需要很长时间才能在 mysql 中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在 MYSQL 查询 中使用 RAND 函数.如果我在 sql 查询中使用这个函数,那么这需要大约 0.7962 秒.但是如果我不使用它,那么这个工作可以在 0.0009 秒内正常工作.如何使用 RAND 函数使 sql 查询更快.

I have to use RAND function in MYSQL query. If I use this function in sql query then this take near about 0.7962 sec. But if I use it without then this work fine with 0.0009 sec. How I can make sql query faster with RAND function.

我的查询

  SELECT 
         posts.ID,
         posts.post_content, 
         posts.post_title, 
         posts.post_date, 
         posts.post_name 
    FROM posts 
         WHERE posts.post_type = 'post' 
         AND posts.post_status = 'publish' 
    ORDER BY RAND() LIMIT 0, 24 

推荐答案

我去解决方案.

 SELECT p1.ID, p1.post_content, p1.post_title, p1.post_date, p1.post_name
     FROM posts as p1 JOIN
          (SELECT CEIL(RAND() *
                 (SELECT MAX(ID)
                    FROM posts)) AS id)
          AS p2
  WHERE p1.ID >= p2.id
  ORDER BY p1.ID ASC
  LIMIT 0, 24

这比我的查询快.

MySQL 快速从 600K 行中随机选择 10 行

这是解决方案.

谢谢

这篇关于ORDER BY RAND() 函数需要很长时间才能在 mysql 中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆