Merging Concatenating JSON(B) columns in query

后端 未结 10 1563
不思量自难忘°
不思量自难忘° 2020-12-08 09:40

Using Postgres 9.4, I am looking for a way to merge two (or more) json or jsonb columns in a query. Consider the following table as an example:

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 10:05

    In Postgres 9.5+ you can merge JSONB like this:

    select json1 || json2;
    

    Or, if it's JSON, coerce to JSONB if necessary:

    select json1::jsonb || json2::jsonb;
    

    Or:

    select COALESCE(json1::jsonb||json2::jsonb, json1::jsonb, json2::jsonb);
    

    (Otherwise, any null value in json1 or json2 returns an empty row)

    For example:

    select data || '{"foo":"bar"}'::jsonb from photos limit 1;
                                   ?column?
    ----------------------------------------------------------------------
     {"foo": "bar", "preview_url": "https://unsplash.it/500/720/123"}
    

    Kudos to @MattZukowski for pointing this out in a comment.

提交回复
热议问题