SQLite - ORDER BY RAND() [英] SQLite - ORDER BY RAND()
问题描述
在MySQL中,我可以使用RAND()函数,在SQLite 3中有什么替代方案吗?
href =http://www.sqlite.org/lang_corefunc.html =noreferrer> random():
SELECT foo FROM bar
WHERE id> =(abs(random())%(SELECT max(id)FROM bar))
LIMIT 1;
/ strong>由于 SQLite自动增量列的文档表明:
上述正常的ROWID选择算法将生成
单调增加的唯一ROWIDs,只要你从不使用
最大ROWID值,并且从不删除表中的条目,
是最大的ROWID。 如果您删除了行,则系统会在创建新行时重新使用
之前删除的行中的ROWID 。
$ b b如果你没有一个
INTEGER PRIMARY KEY AUTOINCREMENT
列(它仍然适用于INTEGER PRIMARY KEY
列)。无论如何,这应该更可移植/可靠:SELECT foo FROM bar
WHERE _ROWID_> = random())%(SELECT max(_ROWID_)FROM bar))
LIMIT 1;
ROWID
,_ROWID _
和OID
都是SQLite内部行标识的别名。In MySQL I can use the RAND() function, is there any alternative in SQLite 3?
解决方案using random():
SELECT foo FROM bar WHERE id >= (abs(random()) % (SELECT max(id) FROM bar)) LIMIT 1;
EDIT (by QOP): Since the docs on SQLite Autoincremented columns states that:
The normal ROWID selection algorithm described above will generate monotonically increasing unique ROWIDs as long as you never use the maximum ROWID value and you never delete the entry in the table with the largest ROWID. If you ever delete rows, then ROWIDs from previously deleted rows might be reused when creating new rows.
The above is only true if you don't have a
INTEGER PRIMARY KEY AUTOINCREMENT
column (it will still work fine withINTEGER PRIMARY KEY
columns). Anyway, this should be more portable / reliable:SELECT foo FROM bar WHERE _ROWID_ >= (abs(random()) % (SELECT max(_ROWID_) FROM bar)) LIMIT 1;
ROWID
,_ROWID_
andOID
are all aliases for the SQLite internal row id.这篇关于SQLite - ORDER BY RAND()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!