简体   繁体   中英

How to change value in array column in postgresql

I have

crew_member_ids                integer[],

column in table. And want to change all entry of specific id (for example 1) to another id (for example 10)

{} - > {}
{1, 2} -> {10, 2}
{2, 3}  -> {2, 3}
{1} -> {10}

How can i do it ?


So far I managed only to select lines to be affected with

select * from initial_costs where 1 = any(crew_member_ids);

tables for test

create table test_tabe(crew_member_ids integer[]);
insert into test_tabe values (ARRAY[3,7,4]),(ARRAY[1,8,4]),(ARRAY[1,5]),(ARRAY[8,10,2]);
 crew_member_ids
-----------------
 {3,7,4}
 {1,8,4}
 {1,5}
 {8,10,2}

cahnge query

update test_tabe set crew_member_ids[1]=10 where array_position(crew_member_ids,1)=1;
 crew_member_ids
-----------------
 {3,7,4}
 {8,10,2}
 {10,8,4}
 {10,5}
update initial_costs 
set crew_member_ids = array_replace(crew_member_ids, 1, 10) 
where 1 = any(crew_member_ids);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM