加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – 使用setseed随机发布postgres

发布时间:2020-12-13 16:01:37 所属栏目:百科 来源:网络整理
导读:我想使用setseed将一个带有随机数的列添加到表中. 原始表结构(test_input)col_a,col_b,col_c 期望的输出(test_output)col_a,col_c,random_id 以下内容在所有行上返回相同的random_id,而不是在每行中返回不同的值. select col_a,setseed(0.5),( select random
我想使用setseed将一个带有随机数的列添加到表中.

原始表结构(test_input)col_a,col_b,col_c

期望的输出(test_output)col_a,col_c,random_id

以下内容在所有行上返回相同的random_id,而不是在每行中返回不同的值.

select col_a,setseed(0.5),(
     select random() from generate_series(1,100) limit 1
     ) as random_id 
from test_input

你能帮我修改使用setseed的查询并在每一行中返回不同的random_id吗?

解决方法

您必须以不同方式使用 setseed.您的示例中也会错误地使用generate_series().你需要使用类似的东西:

select setseed(0.5);

select col_a,random() as random_id from test_input;

如果要将相同的随机数分配给同一行,则必须先对行进行排序,引用documentation:

If the ORDER BY clause is specified,the returned rows are sorted in
the specified order. If ORDER BY is not given,the rows are returned
in whatever order the system finds fastest to produce.

您可以使用:

select setseed(0.5);

select *,random() as random_id from (        
select col_a,col_c from test_input order by col_a,col_c) a;

在这里,我假设col_a,col_c的组合是唯一的.如果不是这种情况,则必须首先向表中添加具有唯一ID的另一列,并在上面的查询中按此列进行排序.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读