问题
(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