Select random row(s) in SQLite

后端 未结 5 894
感动是毒
感动是毒 2020-11-27 03:29

In MySQL, you can select X random rows with the following statement:

SELECT * FROM table ORDER BY RAND() LIMIT X

This does not, however, wo

相关标签:
5条回答
  • 2020-11-27 04:05
    SELECT * FROM table ORDER BY RANDOM() LIMIT 1
    
    0 讨论(0)
  • 2020-11-27 04:05

    This one solves the negative RANDOM integers, and keeps good performance on large datasets:

    SELECT * FROM table LIMIT 1 OFFSET abs(random() % (select count(*) from table));
    

    where:
    abs(random() % n ) Gives you a positive integer in range(0,n)

    0 讨论(0)
  • 2020-11-27 04:10

    SELECT * FROM table ORDER BY RANDOM() LIMIT X

    0 讨论(0)
  • 2020-11-27 04:14

    For a much better performance use:

    SELECT * FROM table WHERE id IN (SELECT id FROM table ORDER BY RANDOM() LIMIT x)
    

    SQL engines first load projected fields of rows to memory then sort them, here we just do a random sort on id field of each row which is in memory because it's indexed, then separate X of them, and find the whole row using these X ids.

    So this consume less RAM and CPU as table grows!

    0 讨论(0)
  • 2020-11-27 04:18

    All answers here are based on ORDER BY. This is very inefficient (i.e. unusable) for large sets because you will evaluate RANDOM() for each record, and then ORDER BY which is a resource expensive operation.

    An other approach is to place abs(CAST(random() AS REAL))/9223372036854775808 < 0.5 in the WHERE clause to get in this case for example 0.5 hit chance.

    SELECT *
    FROM table
    WHERE abs(CAST(random() AS REAL))/9223372036854775808 < 0.5
    

    The large number is the maximum absolute number that random() can produce. The abs() is because it is signed. Result is a uniformly distributed random variable between 0 and 1.

    This has its drawbacks. You can not guarantee a result and if the threshold is large compared to the table, the selected data will be skewed towards the start of the table. But in some carefully designed situations, it can be a feasible option.

    0 讨论(0)
提交回复
热议问题