Looping inside a Postgres UPDATE query

匆匆过客 提交于 2020-02-05 05:15:29

问题


(Postgres 10.10) I have the following fields in my_table:

loval INTEGER 
hival INTEGER 
valcount INTEGER 
values INTEGER[]

I need to set values to an array containing valcount random integers each between loval and hival inclusive. So for:

loval: 3 
hival: 22 
valcount: 6

I'm looking to set values to something like:

{3, 6, 6, 13, 17, 22}

I know how to do this with an inefficient "loop through the cursor" solution, but I'm wondering if Postgres has a way to do a looping computation inline.

Note: I looked at generate_series, but I don't think it produces what I need.


回答1:


generate_series() is indeed the solution:

update my_table
  set "values" = array(select (random() * (hival - loval) + loval)::int 
                       from generate_series(1, valcount));

Online example


Note that values is a reserved keyword, it's not a good idea to use that as a column name.



来源:https://stackoverflow.com/questions/59431856/looping-inside-a-postgres-update-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!