首页 文章

PostgreSQL使用另一列的值更新JSONB列

提问于
浏览
4

我想将数据从一列(varchar)迁移到另一列(jsonb)

Column   |            Type             |                       Modifiers                        
------------+-----------------------------+--------------------------------------------------------
 id         | integer                     | not null default nextval('merchants_id_seq'::regclass)
 name       | character varying           | not null
 nameb      | jsonb                       | not null default '{}'::jsonb

因此 nameb 将成为 {"en": "$name"} ,其中 $namename 字段中的值 .

例如:

SELECT name,nameb

before:

name                 |   nameb    
--------------------------------------+------------
 hello                                | {} 
 world                                | {}

after:

name                 |   nameb    
--------------------------------------+------------
 hello                                | {"en": "hello"}
 world                                | {"en": "world"}

使用regualar类型我可以做 UPDATE SET whatever = (SELECT ...) ,但如何用jsonb做到这一点?

UPDATE merchants SET nameb = (SELECT '{"en": "fillme!"}'::jsonb); 有效,但如何从另一个字段设置"fillme!"值?

1 回答

  • 1

    我找到了解决方案

    UPDATE merchants AS m1 
    SET nameb = (
      SELECT row_to_json(t) FROM (
        SELECT name as en FROM merchants AS m2 WHERE m1.id = m2.id
      ) t
    )::jsonb;
    

    不确定它是否正确,但它确实有效

相关问题