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

前端 未结 8 2293
天命终不由人
天命终不由人 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:20

    This will give you single sub query that will use the index to get a random id then the other query will fire getting your joined table.

    SELECT  accomodation.ac_id,
            accomodation.ac_status,
            accomodation.ac_name,
            accomodation.ac_status,
            accomodation.ac_images
    FROM    accomodation, accomodation_category
    WHERE   accomodation.ac_status != 'draft'
            AND accomodation.ac_category = accomodation_category.acat_id
            AND accomodation_category.acat_slug != 'vendeglatohely'
            AND ac_images != 'b:0;'
    AND accomodation.ac_id IS IN (
            SELECT accomodation.ac_id FROM accomodation ORDER BY RAND() LIMIT 1
    )
    

提交回复
热议问题