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

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

    Try this:

    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
    

    This is especially efficient on MyISAM (since the COUNT(*) is instant), but even in InnoDB it's 10 times more efficient than ORDER BY RAND().

    The main idea here is that we don't sort, but instead keep two variables and calculate the running probability of a row to be selected on the current step.

    See this article in my blog for more detail:

    • Selecting random rows

    Update:

    If you need to select but a single random record, try this:

    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
            )
            )
    

    This assumes your ac_id's are distributed more or less evenly.

提交回复
热议问题