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()
基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01