Postgresql 用随机值更新每一行 [英] Postgresql update each row with a random value

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

问题描述

这与其他问题类似,但它似乎因逐个数据库的实现而异.我正在使用 postgres,NEWID 之类的东西似乎不存在.

This is similar to other questions but it appears to vary on a database-by-database implementation. I am using postgres and things like NEWID do not appear to exist.

这就是我想要的工作:

update foo set bar = (select floor(random() * 10) + 1);

我理解为什么没有,但我似乎找不到适用于 Postgres 的合适解决方案.我希望 bar 的值是 1 到 10 之间的随机数,行不同.

I understand why it doesn't but I can't seem to find a suitable solution that works for Postgres. I want the value of bar to be a random number between 1 and 10 that differs per row.

推荐答案

我认为 Postgres 可能会优化子查询.这不行吗?

I think that Postgres might optimize the subquery. Doesn't this work?

update foo
   set bar = floor(random() * 9 + 1);  -- from 1 to 10, inclusive

这篇关于Postgresql 用随机值更新每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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