【问题标题】:Postgresql Join elements by key with json fieldsPostgresql 通过 json 字段键连接元素
【发布时间】:2019-08-27 15:56:05
【问题描述】:

使用 json 字段键连接元素

CREATE TABLE customer_json (
   ID serial NOT NULL PRIMARY KEY,
   info json NOT NULL
);


INSERT INTO customer_json (info) VALUES ('{ "customer": ["John Doe"]}');
INSERT INTO customer_json (info) VALUES ('{ "customer": ["Peter Doe"]}');
INSERT INTO customer_json (info) VALUES ('{ "customer": ["Welsey Doe"]}');
select  json_agg(info) from customer_json

结果:

[
   { "customer": ["John Doe"]},
   { "customer": ["Peter Doe"]},
   { "customer": ["Welsey Doe"]}
]

通缉:

[
   { "customer": [
                    "John Doe",
                    "Peter Doe",
                    "Welsey Doe"
                 ]
   }
]

【问题讨论】:

    标签: json postgresql aggregate


    【解决方案1】:

    demo:db<>fiddle

    SELECT
        json_agg(object)
    FROM (
        SELECT
            json_build_object(
                'customer',
               json_agg(info -> 'customer' -> 0)
            ) as object
        FROM 
            customer_json
    ) s
    
    1. 获取带有info -&gt; 'customer' -&gt; 0的名称(先获取customer的值JSON数组,然后获取它们的第一个值)
    2. json_agg()将它们聚合成一个JSON数组
    3. 使用 json_build_object() 构建一个新的 JSON 对象,并将步骤 2 中的新数组作为值
    4. 因为您想将此客户对象放入第二个数组,您可以使用高级查询将json_agg() 作为第二组。

    或者,您可以在特殊情况下使用 json_build_array(),而不是执行第 4 步:

    demo:db<>fiddle

    SELECT
        json_build_array(
            json_build_object(
                'customer',
               json_agg(info -> 'customer' -> 0)
            )
         )
    FROM 
        customer_json
    

    【讨论】:

    • @TiagoSa 这有帮助吗?应该改变什么吗?请不要忘记支持任何有帮助的答案。这会尊重回复者在您的问题上花费的时间和工作。如果一个答案解决了您的问题,那么请不要忘记也接受它,以关闭问题。
    猜你喜欢
    • 1970-01-01
    • 2013-10-25
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多