MySQL: Alternatives to ORDER BY RAND()

前端 未结 7 1764
情歌与酒
情歌与酒 2020-11-22 02:46

I\'ve read about a few alternatives to MySQL\'s ORDER BY RAND() function, but most of the alternatives apply only to where on a single random result is needed.

7条回答
  •  甜味超标
    2020-11-22 03:23

    It is not the fastest, but faster then common ORDER BY RAND() way:

    ORDER BY RAND() is not so slow, when you use it to find only indexed column. You can take all your ids in one query like this:

    SELECT id
    FROM testTable
    ORDER BY RAND();
    

    to get a sequence of random ids, and JOIN the result to another query with other SELECT or WHERE parameters:

    SELECT t.*
    FROM testTable t
    JOIN
        (SELECT id
        FROM `testTable`
        ORDER BY RAND()) AS z ON z.id= t.id   
    WHERE t.isVisible = 1
    LIMIT 100; 
    

    in your case it would be:

    SELECT u.id, p.photo 
    FROM users u, profiles p 
    JOIN
        (SELECT id
        FROM users
        ORDER BY RAND()) AS z ON z.id = u.id   
    WHERE p.memberid = u.id 
      AND p.photo != '' 
      AND (u.ownership=1 OR u.stamp=1) 
    LIMIT 18 
    

    It's very blunt method and it can be not proper with very big tables, but still it's faster than common RAND(). I got 20 times faster execution time searching 3000 random rows in almost 400000.

提交回复
热议问题