gpt4 book ai didi

PostgreSQL 9.6 中的 JSON 查询

转载 作者:行者123 更新时间:2023-11-29 12:42:18 25 4
gpt4 key购买 nike

假定以下数据:

select * from orderlist ;
id | orders | orderenvelope_id
----+--------------------------------------------+------------------
14 | { +| 13
| "orders" : [ { +|
| "orderType" : "OfferPurchaseOrder", +|
| "duration" : 1494413009450, +|
| "currencyCode" : "EUR" +|
| }, { +|
| "orderType" : "CustomerCreationOrder",+|
| "customerData" : { +|
| "customerType" : "PERSONAL_ACCOUNT",+|
| "contactData" : { +|
| "contactQuality" : "VALID", +|
| "firstName" : "Peter", +|
| "lastName" : "Pan" +|
| } +|
| } +|
| } ] +|
| } |

我想获得'OfferPurchaseOrder';因此使用了以下 SELECT:

 select id, orderenvelope_id, o from orderlist list, json_array_elements(list.orders->'orders') as o where o->>'orderType' = 'OfferPurchaseOrder';

id | orderenvelope_id | o
----+------------------+-----------------------------------------
14 | 13 | { +
| | "orderType" : "OfferPurchaseOrder",+
| | "duration" : 1494413009450, +
| | "currencyCode" : "EUR" +
| | }

看起来好像很有魅力,只有一件事:我想与 Hibernate 集成,所以该列应该命名为“orders”而不是“o”(就像在初始选择中那样);否则 Hibernate 将无法正确映射这些东西。除此之外,“简化的”JSON 列表应该在那里,因此所需的结果应该如下所示:

 id | orderenvelope_id |                    orders              |            
----+------------------+----------------------------------------+
14 | 13 | "orders" : [{ +
| | "orderType" : "OfferPurchaseOrder",+
| | "duration" : 1494413009450, +
| | "currencyCode" : "EUR" +
| | } +
| |]

有什么提示吗?

谢谢和问候副指挥官

最佳答案

如果你可以移动到 jsonb 类型而不是查询可以看起来像:

WITH x AS (
SELECT id, orderenvelope_id, o
FROM orderlist list, jsonb_array_elements(list.orders->'orders') as o
WHERE o->>'orderType' = 'OfferPurchaseOrder'
)
SELECT id, orderenvelope_id, jsonb_set('{}'::jsonb, '{orders}'::text[], jsonb_agg(o))
FROM x
GROUP BY 1,2
;

但是,如果您不能使用 jsonb,只需将文本转换为 json:

WITH x AS (
SELECT id, orderenvelope_id, o
FROM orderlist list, json_array_elements(list.orders->'orders') as o
WHERE o->>'orderType' = 'OfferPurchaseOrder'
)
SELECT id, orderenvelope_id, ('{"orders": ' || json_agg(o) ||'}')::json
FROM x
GROUP BY 1,2
;

关于PostgreSQL 9.6 中的 JSON 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43892413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com