Postgresql用随机值更新每一行

dre*_*ver 12 sql postgresql

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

这就是我想要的工作:

update foo set bar = (select floor(random() * 10) + 1);
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*off 23

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

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


小智 6

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

update foo set bar = (select floor(random() * 10) + 1 where foo.id = foo.id);
Run Code Online (Sandbox Code Playgroud)