在 SQLite 中选择随机行 [英] Select random row(s) in SQLite

查看:48
本文介绍了在 SQLite 中选择随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MySQL 中,您可以使用以下语句随机选择 X 行:

In MySQL, you can select X random rows with the following statement:

SELECT * FROM table ORDER BY RAND() LIMIT X

然而,这在 SQLite 中不起作用.有等价的吗?

This does not, however, work in SQLite. Is there an equivalent?

推荐答案

为了更好的性能使用:

SELECT * FROM table WHERE id IN (SELECT id FROM table ORDER BY RANDOM() LIMIT x)

SQL 引擎首先将行的投影字段加载到内存中,然后对它们进行排序,这里我们只是对内存中的每一行的 id 字段进行随机排序,因为它已被索引,然后将其中的 X 个分开,并使用这些 X id 查找整行.

SQL engines first load projected fields of rows to memory then sort them, here we just do a random sort on id field of each row which is in memory because it's indexed, then separate X of them, and find the whole row using these X ids.

因此,随着表的增长,这会消耗更少的 RAM 和 CPU!

So this consume less RAM and CPU as table grows!

这篇关于在 SQLite 中选择随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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