有没有办法从PL/PGSQL中的光标中获取随机元素?

发布于 2025-02-10 04:12:10 字数 108 浏览 0 评论 0原文

我正在研究PostgreSQL中的示例,在与光标打交道时,我找不到一种获取单个随机元素的方法。

我已经看到了许多文章和文档,但是似乎没有办法这样做。输出将是光标的随机数,即光标的随机元素。

I'm studying examples in PostgreSQL, and I can't find a way to get a single random element when dealing with a cursor.

I have seen many articles and documentation, but there seems to be no way to do it.The output would be a random number from the cursor, that is, a random element from the cursor.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看透却不说透 2025-02-17 04:12:10

不要使用光标。而是使用返回单个随机值并将其分配给变量的查询:

num1 := (select num from client order by random() limit 1);

Don't use a cursor. Instead, use a query that returns a single random value and assign it to a variable:

num1 := (select num from client order by random() limit 1);
静谧幽蓝 2025-02-17 04:12:10

使用本地表的测试案例:

do $
DECLARE 
    rec record;
    num1 integer;
    ct integer;
    cur1 CURSOR FOR
        SELECT p_item_no FROM plant1;
    fetch_ct integer;
BEGIN
    SELECT INTO ct count(*) from plant1;
    SELECT INTO fetch_ct (random() * ct)::integer;
    open cur1;
    fetch relative fetch_ct from cur1 into rec;
    num1 = rec.p_item_no;
    Raise Notice 'Num: %', num1;

close cur1;

end $ 
Language 'plpgsql';

NOTICE:  Num: 2742
DO

--Running it again

NOTICE:  Num: 3083
DO
--And again
NOTICE:  Num: 4848
DO


A test case using a local table:

do $
DECLARE 
    rec record;
    num1 integer;
    ct integer;
    cur1 CURSOR FOR
        SELECT p_item_no FROM plant1;
    fetch_ct integer;
BEGIN
    SELECT INTO ct count(*) from plant1;
    SELECT INTO fetch_ct (random() * ct)::integer;
    open cur1;
    fetch relative fetch_ct from cur1 into rec;
    num1 = rec.p_item_no;
    Raise Notice 'Num: %', num1;

close cur1;

end $ 
Language 'plpgsql';

NOTICE:  Num: 2742
DO

--Running it again

NOTICE:  Num: 3083
DO
--And again
NOTICE:  Num: 4848
DO


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文