V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
imherer

PostgreSQL 里对 json 多个 key 同时操作如何用一条 SQL 完成

  •  
  •   imherer · Jul 8, 2019 · 3910 views
    This topic created in 2493 days ago, the information mentioned may be changed or developed.

    格式是jsonb,数据如下:

    {"1003": 100, "1004": 100, "1005": 100, "1006": 100, "1007": 100, "1008": 100}

    假如我现在想把1003,1004的数量更新成 200,同时将1005删除,一条 SQL 如何实现呢?

    只操作一个 key 可以这样实现,但是多个怎么实现呢?

    UPDATE table SET field = JSONB_SET(field, '{1003}','200',true)

    3 replies    2019-07-08 17:05:05 +08:00
    Takamine
        1
    Takamine  
       Jul 8, 2019
    同时更新多个字段:
    UPDATE table SET field = field || '{"1003":200 ,"1004":200}'::jsonb where xxxxxx。
    感觉把两个不同的 DML 操作丢一起不太好。
    imherer
        2
    imherer  
    OP
       Jul 8, 2019
    @Takamine 嗯,谢谢,已经解决了

    因为在实际业务中,有可能会出现数量减少的情况。 当数量减到 0 的时候,就要把这个 key 删掉。
    这样就出现了,有的 key 是更新数量,有的 key 是直接删除

    要是不放一起的话,实际上是更新同一个字段,但是分 2 条 SQL 分别操作 2 次数据库,是不是也不太好?
    reus
        3
    reus  
       Jul 8, 2019
    update table set filed = jsonb_strip_nulls(field || '{"1003": 200, "1004": 200, "1005": null}')
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3498 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 00:10 · PVG 08:10 · LAX 17:10 · JFK 20:10
    ♥ Do have faith in what you're doing.