我认为可以使用普通的UPDATE。
让我们尝试选择我们需要替换的项目:
-- first, second and third item from array and convert to string
SELECT array_to_string(weather[1:1], ',') AS KS,
array_to_string(weather[2:2], ',') AS MO,
array_to_string(weather[3:3], ',') AS CA
FROM test_tbl;
结果:"KS,'S'","MO,'S'","CA,'S'"
现在我们可以选择记录记录进行更新,只需将字符串与数组项(作为字符串)进行比较:
SELECT * FROM test_tbl
-- KS,'S'
WHERE array_to_string(weather[1:1], ',') = concat('KS,', quote_literal('S'))
-- MO,'S'
-- array_to_string(weather[2:2], ',') = concat('MO,', quote_literal('S'))
-- CA,'S'
-- array_to_string(weather[3:3], ',') = concat('CA,', quote_literal('S'))
好的。现在我们只需要将数组按部分与新项目合并。
UPDATE test_tbl
-- generate first item + other items
SET weather = string_to_array(concat('KS,', quote_literal('W')), ',')::varchar[] || weather[2:]
WHERE array_to_string(weather[1:1], ',') = concat('KS,', quote_literal('S'));
UPDATE test_tbl
-- first item + generate second + other items
SET weather = weather[1:1] || string_to_array(concat('MO,', quote_literal('W')), ',')::varchar[] || weather[3:]
WHERE array_to_string(weather[2:2], ',') = concat('MO,', quote_literal('S'));
UPDATE test_tbl
-- first + second items, generate third + other items
SET weather = weather[0:2] || string_to_array(concat('CA,', quote_literal('W')), ',')::varchar[] || weather[4:]
WHERE array_to_string(weather[3:3], ',') = concat('CA,', quote_literal('S'));
结果:{{KS,'W'},{MO,'W'},{CA,'W'}}。希望这会有所帮助