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

问题描述

我在 postgres 中有一个包含几百万行的表.我在网上查了一下,发现了以下内容

I have a table in postgres that contains couple of millions of rows. I have checked on the internet and I found the following

SELECT myid FROM mytable ORDER BY RANDOM() LIMIT 1;

它可以工作,但它真的很慢......是否有另一种方法可以进行该查询,或者直接选择随机行而不读取所有表的方法?顺便说一下,'myid' 是一个整数,但它可以是一个空字段.

It works, but it's really slow... is there another way to make that query, or a direct way to select a random row without reading all the table? By the way 'myid' is an integer but it can be an empty field.

推荐答案

您可能想尝试使用 OFFSET,如

You might want to experiment with OFFSET, as in

SELECT myid FROM mytable OFFSET floor(random() * N) LIMIT 1;

Nmytable 中的行数.你可能需要先做一个 SELECT COUNT(*) 来找出 N 的值.

The N is the number of rows in mytable. You may need to first do a SELECT COUNT(*) to figure out the value of N.

更新(安东尼·哈奇金斯)

您必须在此处使用 floor:

SELECT myid FROM mytable OFFSET floor(random() * N) LIMIT 1;

考虑一个 2 行的表格;random()*N 生成 0 <= x <2 和例如 SELECT myid FROM mytable OFFSET 1.7 LIMIT 1; 由于隐式四舍五入到最接近的整数而返回 0 行.

Consider a table of 2 rows; random()*N generates 0 <= x < 2 and for example SELECT myid FROM mytable OFFSET 1.7 LIMIT 1; returns 0 rows because of implicit rounding to nearest int.

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

05-28 18:01
查看更多