开发者

sqlite return a random record in a table

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜