SQLite - 按 RAND 排序()
在 MySQL 中我可以使用 RAND() 函数,SQLite 3 中有其他替代方法吗?
In MySQL I can use the RAND() function, is there any alternative in SQLite 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 random():
编辑(按 QOP): 自文档以来在 SQLite 自动增量ed 列上指出:
仅当您没有
INTEGER PRIMARY KEY AUTOINCRMENT
列时,上述情况才成立(它仍然可以与INTEGER PRIMARY KEY
列一起正常工作)。 无论如何,这应该更便携/可靠:ROWID
、_ROWID_
和OID
都是 SQLite 内部行 id 的别名。using random():
EDIT (by QOP): Since the docs on SQLite Autoincremented columns states that:
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:ROWID
,_ROWID_
andOID
are all aliases for the SQLite internal row id.为了获得更好的性能,请在 SQLite 中使用它:
这也适用于 MySQL。 这运行得更快,因为SQL引擎首先将行的投影字段加载到内存中,然后对它们进行排序,这里我们只是加载并随机排序行的id字段,然后我们得到其中的X个,并找到整行这些 X id 默认情况下已建立索引。
For a much better performance use this in SQLite:
This is also applicable to MySQL. This runs faster because SQL engines first load projected fields of rows to memory then sort them, here we just load and random sort the id field of rows, then we get X of them, and find the whole rows of these X ids which is by default indexed.
解决了:
Solved:
目标是获得随机结果(无限滚动),同时能够对结果进行 SQL 分页(
LIMIT a,b
),这需要可预测的结果(伪随机又名 PRNG)。SIN(id + seed)
似乎是RANDOM(seed)
的一个很好的替代方案。请考虑这个完全用 JS 编写的演示,它使用
SIN(id + Seed)
评分模拟ORDER BY
子句:The goal is to get random results (Infinite Scroll) while being able to SQL paginate the results (
LIMIT a,b
), which needs a predictible outcome (pseudorandom aka PRNG).SIN(id + seed)
seems a great alternative toRANDOM(seed)
.Please consider this demo entirely written in JS that simulates an
ORDER BY
clause using aSIN(id + seed)
scoring :