Postgresql

Postgres JSONB - 展平嵌套對象和分組

  • September 24, 2020

據我所知,如果我需要展平包含在我的 postgres 數據庫表的特定欄位中的 JSON,我可以使用以下函式/運算符之一

現在,這些函式非常適合像這樣簡單的扁平化:

{
  "manufacturer":[
     {
        "manufacturer":"Tesla",
        "address":"Deer Creek Road Palo Alto",
        "contact":"support@tesla.com"
     },
     {
        "manufacturer":"BMW",
        "address":"Petuelring 130, 80809 München",
        "contact":"support@bmw.com"
     }
  ]
}

使用該jsonb_to_recordset函式,json 將被展平,沒有任何問題。

現在,我的有效問題來了,我無法解決以有效解決這個問題……

假設每個製造商都有一個嵌套的 JSON 對象,該對象公開模型和起始價格,如以下 JSON 中報告的

{
  "cars":[
     {
        "manufacturer":"Tesla",
        "address":"Deer Creek Road Palo Alto",
        "contact":"support@tesla.com",
        "models":[
           {
              "model":"Model S",
              "starting_price":50000
           },
           {
              "model":"Model 3",
              "starting_price":35000
           },
           {
              "model":"Model X",
              "starting_price":70000
           }
        ]
     },
     {
        "manufacturer":"BMW",
        "address":"Petuelring 130, 80809 München",
        "contact":"support@bmw.com",
        "models":[
           {
              "model":"X1",
              "starting_price":35000
           },
           {
              "model":"X2",
              "starting_price":32000
           },
           {
              "model":"X3",
              "starting_price":39000
           },
           {
              "model":"Series 5",
              "starting_price":55000
           },
           {
              "model":"Series 3",
              "starting_price":50000
           }
        ]
     }
  ]
}

我如何創建一個查詢,該查詢還可以models有效地展平對象並輸出許多行作為對像中報告的製造商模型models

嵌套 JSON 展平

獎金問題:

除此之外,可以創建一個查詢,以更緊湊的方式輸出類似這樣的內容,如下所示對行進行分組?

行分組

任何幫助表示讚賞!

您需要取消嵌套兩次:

select x.m ->> 'manufacturer' as manufacturer,
      x.m ->> 'address' as address,
      x.m ->> 'contact' as contact,
      m.model ->> 'model' as model,
      (m.model ->> 'starting_price')::int as starting_price
from the_table t
 cross join jsonb_array_elements(t.models -> 'cars') as x(m)
 cross join jsonb_array_elements(x.m -> 'models') as m(model)

當您在應用程序中而不是在 SQL 中顯示數據時,最好抑制重複值。

線上範例

引用自:https://dba.stackexchange.com/questions/276002