Postgresql 用随机值更新每一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36463205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:13:52  来源:igfitidea点击:

Postgresql update each row with a random value

sqlpostgresql

提问by dreamriver

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

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

This is what I want to work:

这就是我想要的工作:

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

I understand whyit doesn't but I can't seem to find a suitable solution that works for Postgres. I want the value of barto be a random number between 1 and 10 that differs perrow.

我明白为什么没有,但我似乎无法找到适用于 Postgres 的合适解决方案。我希望 的值是bar1 到 10 之间的随机数,行不同。

回答by Gordon Linoff

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

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

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

回答by Alexey Khivin

For PostgreSQL (tested on 9.5) this can be solved by adding fake "where" clause

对于 PostgreSQL(在 9.5 上测试),这可以通过添加假“where”子句来解决

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