How can i optimize MySQL's ORDER BY RAND() function?

前端 未结 8 2277
天命终不由人
天命终不由人 2020-11-22 00:58

I\'d like to optimize my queries so I look into mysql-slow.log.

Most of my slow queries contains ORDER BY RAND(). I cannot find a real solu

8条回答
  •  梦如初夏
    2020-11-22 01:13

    Here's how I'd do it:

    SET @r := (SELECT ROUND(RAND() * (SELECT COUNT(*)
      FROM    accomodation a
      JOIN    accomodation_category c
        ON (a.ac_category = c.acat_id)
      WHERE   a.ac_status != 'draft'
            AND c.acat_slug != 'vendeglatohely'
            AND a.ac_images != 'b:0;';
    
    SET @sql := CONCAT('
      SELECT  a.ac_id,
            a.ac_status,
            a.ac_name,
            a.ac_status,
            a.ac_images
      FROM    accomodation a
      JOIN    accomodation_category c
        ON (a.ac_category = c.acat_id)
      WHERE   a.ac_status != ''draft''
            AND c.acat_slug != ''vendeglatohely''
            AND a.ac_images != ''b:0;''
      LIMIT ', @r, ', 1');
    
    PREPARE stmt1 FROM @sql;
    
    EXECUTE stmt1;
    

提交回复
热议问题