MySQL: Alternatives to ORDER BY RAND()

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

    I ran into this today and was trying to use 'DISTINCT' along with JOINs, but was getting duplicates I assume because the RAND was making each JOINed row distinct. I muddled around a bit and found a solution that works, like this:

    SELECT DISTINCT t.id, 
                    t.photo 
           FROM (SELECT  u.id, 
                         p.photo,
                         RAND() as rand
                    FROM users u, profiles p 
                     WHERE p.memberid = u.id 
                      AND p.photo != '' 
                      AND (u.ownership=1 OR u.stamp=1)
                    ORDER BY rand) t
           LIMIT 18
    
    0 讨论(0)
提交回复
热议问题