【问题标题】:How to change value in array column in postgresql如何在postgresql中更改数组列中的值
【发布时间】:2021-12-26 16:18:56
【问题描述】:

我有

crew_member_ids                integer[],

表格中的列。 并希望将特定id(例如1)的所有条目更改为另一个id(例如10)

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

我该怎么做?


到目前为止,我只设法选择了受影响的行

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

【问题讨论】:

    标签: sql arrays postgresql


    【解决方案1】:

    测试表

    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[1,1,5]),(ARRAY[3,8,20]),(ARRAY[8,10,2]);
    
     crew_member_ids
    -----------------
     {3,7,4}
     {1,8,4}
     {1,5}
     {1,1,5}
     {3,8,20}
     {8,10,2}
    

    更改查询

    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}
     {3,8,20}
     {10,8,4}
     {10,5}
     {10,1,5}
    

    【讨论】:

      【解决方案2】:
      update initial_costs 
      set crew_member_ids = array_replace(crew_member_ids, 1, 10) 
      where 1 = any(crew_member_ids);
      

      【讨论】:

        猜你喜欢
        • 2011-06-12
        • 1970-01-01
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 2017-11-09
        • 1970-01-01
        相关资源
        最近更新 更多