根据其他列POSTGRES中的键值更新表列

时间:2018-02-18 13:03:17

标签: sql json postgresql

我的表名是拥有is_nse,布尔列和交换列类型json的公司,其值类似于" [{" exchange":" NSE","自动收报机":" ABC"},{"交换":" BSE""股票":" ABC&#34 ;}]"

现在我有了这个查询

 update companies set is_nse=0 from (SELECT is_nse, obj.value->>'exchange' As exch FROM  (SELECT * FROM   companies WHERE  sector is not null) u JOIN LATERAL json_array_elements(exchanges) obj(value) ON obj.value->>'exchange' = 'BSE')y 

但它更新了公司表中的所有行而不是子查询的行。可以有人告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:0)

您需要将companies中的updatefrom子句相关联。假设你有一个id,你可以这样做:

update companies
    set is_nse = 0
    from (select c.*
          from companies u join lateral
               json_array_elements(exchanges) obj(value)
               on obj.value->>'exchange' = 'BSE'
          where u.sector is not null
         ) y
    where y.companyid = companies.companyid ;