簡體   English   中英

PostgreSQL從JSONB數組中選擇特定項目

[英]PostgreSQL select specific items from JSONB array

我有一張這樣的桌子:

orders

order_number   products
1234           [{"upc":2434354, "title":"Widget"}]
4321           [{"upc":6434556, "title":"Shorts"}, {"upc":54346, title: "Shirt"}]

我想生成這樣的輸出

[
{order_number: 1234, upc: 2434354},
{order_number: 4321, upc: 6434556}
]

如您所見,我從數組中拉出了UPC(僅針對數組中的第一個元素)。

請注意,如果productsjsonb類型

我嘗試了這個:

SELECT jsonb_array_elements(products)[0]->>upc FROM orders ORDER BY created DESC LIMIT 10

但這給出了語法錯誤,我不確定確切如何在PostgreSQL中進行數組遍歷

另外, products可能為空數組[]

演示:分貝<>小提琴

SELECT
    jsonb_agg(
         jsonb_build_object(
             'order_number', order_number, 
             'upc', products -> 0 -> 'upc'
         )
    )
FROM
    orders
  1. products -> 0 -> 'upc'獲取第一個數組元素的upc
  2. jsonb_build_object()為每條包含order_numberupc值的記錄構建一個JSON對象
  3. jsonb_agg()將這些JSON對象聚合到一個JSON數組中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM