SQLite - ORDER BY RAND()(SQLite - ORDER BY RAND())
问题描述
在 MySQL 中我可以使用 RAND() 函数,在 SQLite 3 中还有其他选择吗?
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;
<小时>
编辑(按 QOP): 由于 SQLite Autoincremented 列指出:
EDIT (by QOP): Since the docs on SQLite Autoincremented columns states that:
上面描述的普通ROWID选择算法会生成只要您从不使用最大 ROWID 值,您永远不会删除表中的条目最大的 ROWID.如果您曾经删除过行,那么 ROWID 来自创建新行时可能会重复使用以前删除的行.
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.
以上仅当您没有 INTEGER PRIMARY KEY AUTOINCREMENT
列时才正确(它仍然可以与 INTEGER PRIMARY KEY
列一起使用).无论如何,这应该更便携/可靠:
The above is only true if you don't have a INTEGER PRIMARY KEY AUTOINCREMENT
column (it will still work fine with INTEGER 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_
和 OID
都是 SQLite 内部行 ID 的别名.
ROWID
, _ROWID_
and OID
are all aliases for the SQLite internal row id.
这篇关于SQLite - ORDER BY RAND()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQLite - ORDER BY RAND()


基础教程推荐
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01