How to request a random row in SQL?

前端 未结 29 2897
孤城傲影
孤城傲影 2020-11-21 06:45

How can I request a random row (or as close to truly random as is possible) in pure SQL?

29条回答
  •  北海茫月
    2020-11-21 07:09

    Insted of using RAND(), as it is not encouraged, you may simply get max ID (=Max):

    SELECT MAX(ID) FROM TABLE;
    

    get a random between 1..Max (=My_Generated_Random)

    My_Generated_Random = rand_in_your_programming_lang_function(1..Max);
    

    and then run this SQL:

    SELECT ID FROM TABLE WHERE ID >= My_Generated_Random ORDER BY ID LIMIT 1
    

    Note that it will check for any rows which Ids are EQUAL or HIGHER than chosen value. It's also possible to hunt for the row down in the table, and get an equal or lower ID than the My_Generated_Random, then modify the query like this:

    SELECT ID FROM TABLE WHERE ID <= My_Generated_Random ORDER BY ID DESC LIMIT 1
    

提交回复
热议问题