ORDER BY RAND() seems to be less than random

后端 未结 2 1219
梦如初夏
梦如初夏 2021-01-18 21:36

I have a fairly simple SQL (MySQL):

SELECT foo FROM bar ORDER BY rank, RAND()

I notice that when I refresh the results, the randomness is s

相关标签:
2条回答
  • 2021-01-18 21:50

    The RAND() can not be refresh for each row. A possible solution might be:

    SELECT foo FROM bar ORDER BY rank, CHECKSUM(NEWID())
    
    0 讨论(0)
  • 2021-01-18 21:51

    RAND() is only executed once per query. You can verify this by looking at the result set.

    If you're trying to get a randomized order, you should be using either NEWID() or CHECKSUM(NEWID()).

    WITH T AS ( -- example using RAND()
      SELECT 'Me' Name UNION SELECT 'You' UNION SELECT 'Another'
    )
    SELECT Name, RAND()
    FROM T;
    
    WITH T AS ( -- example using just NEWID()
      SELECT 'Me' Name UNION SELECT 'You' UNION SELECT 'Another'
    )
    SELECT Name, NEWID()
    FROM T;
    
    WITH T AS ( -- example getting the CHECKSUM() of NEWID()
      SELECT 'Me' Name UNION SELECT 'You' UNION SELECT 'Another'
    )
    SELECT Name, CHECKSUM(NEWID())
    FROM T;
    
    0 讨论(0)
提交回复
热议问题