SQLite - ORDER BY RAND() [英] SQLite - ORDER BY RAND()

查看:32
本文介绍了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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆