MySQL: Alternatives to ORDER BY RAND()

前端 未结 7 1765
情歌与酒
情歌与酒 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:15

    Here's an alternative, but it is still based on using RAND():

      SELECT u.id, 
             p.photo,
             ROUND(RAND() * x.m_id) 'rand_ind'
        FROM users u, 
             profiles p,
             (SELECT MAX(t.id) 'm_id'
                FROM USERS t) x
       WHERE p.memberid = u.id 
         AND p.photo != '' 
         AND (u.ownership=1 OR u.stamp=1) 
    ORDER BY rand_ind
       LIMIT 18
    

    This is slightly more complex, but gave a better distribution of random_ind values:

      SELECT u.id, 
             p.photo,
             FLOOR(1 + RAND() * x.m_id) 'rand_ind'
        FROM users u, 
             profiles p,
             (SELECT MAX(t.id) - 1 'm_id'
                FROM USERS t) x
       WHERE p.memberid = u.id 
         AND p.photo != '' 
         AND (u.ownership=1 OR u.stamp=1) 
    ORDER BY rand_ind
       LIMIT 18
    

提交回复
热议问题