Let's say I have an associative array (defined in another language) like so:
apply = {
'qwer': ['tju', 'snf', 'rjtj', 'sadgg']
'asdf': ['rtj', 'sfm', 'rtjt', 'adjdj']
...
'zxcv': ['qwr', 'trj', '3w4u', '3tt3']
}
And I have a table like so:
CREATE TABLE apples (
id integer,
name varchar(10),
key varchar(10),
value varchar(10)
);
I want to apply an update where if apples.value
is in one of the lists of the apply
variable, then set the apples.key
to the key of the array. If apples.value
was tju
then set apples.key
to qwer
.
My current approach looks like this (mixing PostgreSQL with any procedural language):
for key in apply.keys:
UPDATE apples SET key=$key
FROM (SELECT unnest(array($apply[key])) AS value) AS update_table
WHERE value=update_table.value
I want to do this in a single statement.