简体   繁体   English

在postgres 10中更新jsonb列

[英]updating jsonb column in postgres 10

I'm trying to update a jsonb column in PG10. 我正在尝试更新jsonb中的jsonb列。 I noticed that the following works only if there is some value exists in that column for a given record. 我注意到只有在该列中存在给定记录的某些值时,以下内容才有效。

UPDATE public.mytable SET config = jsonb_set (
    config, '{"data1"}', '{ 
        "text" : "my text"
        }', TRUE) 
WHERE id = 1234;

The update is successful only if the column config is not null. 仅当列config不为空时,更新才成功。 I don't see any errors when I execute the statement though. 我执行语句时没有看到任何错误。

If this column for a given record is empty, I need to do 如果给定记录的此列为空,则需要执行

UPDATE public.mytable SET config = '{ 
   "data1" : {     
        "text" : "my text"
        }
    }' 
WHERE id = 1234;

So my current strategy is to check for non-null and use first or second method to update the column value. 因此,我当前的策略是检查非空值,并使用第一种或第二种方法更新列值。 Is this the right approach? 这是正确的方法吗? Why is the value not updated when I use jsonb_set ? 为什么在使用jsonb_set时未更新该值?

Use COALESCE(config,'{}') 使用COALESCE(config,'{}')

UPDATE mytable SET config = jsonb_set (
    COALESCE(config,'{}'),'{"data1"}', '{ 
        "text" : "my text"
        }', TRUE) 
WHERE id = 1234;

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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