开发者

sqlite return a random record in a table

开发者 https://www.devze.com 2023-04-10 15:59 出处:网络
How do I return a random record in a SQLite table.For example, I 开发者_高级运维have a table with 750 records, I want to return the 657th record.(any record will do).What would be the SQL syntax?I hav

How do I return a random record in a SQLite table. For example, I 开发者_高级运维have a table with 750 records, I want to return the 657th record. (any record will do). What would be the SQL syntax? I have an autoincrementing field as my Id primary key, but I don want to use the key field, since the id use is not recommended. I'll be searching a db in an Android App.

TIA


Try this:

SELECT * FROM table ORDER BY RANDOM() LIMIT 1; 


You may try something like this that should be more efficient

select * from table
   where rowid =
      (select round(abs(random()/9223372036854775807.0)*max(rowid)+1) from table);

If you have deleted rows this select might return no rows, so if this is the case you may need to requery.

0

精彩评论

暂无评论...
验证码 换一张
取 消