簡體   English   中英

Select 來自 JSON 數組的唯一值 - PostgreSQL Z0ECD11C1D7A287401D148A23BBD7A 列

[英]Select Unique value from a JSON Array - PostgreSQL JSON column

我有以下 JSON 文檔存儲在 PostgreSQL JSON 列中:

{
  "status": "Success",
  "message": "",
  "data": {
    "serverIp": "XXXX",
    "ruleId": 32321,
    "results": [
      {
        "versionId": 555555,
        "PriceID": "8abf35ec-3e0e-466b-a4e5-2af568e90eec",
        "price": 350,
        "Convert": 0.8,
        "Cost": 15
        "Customer_ID":1
      },
      {
        "versionId": 4444,
        "PriceID": "b5a1dbd5-17b4-4847-8b3c-da334f95276a",
        "price": 550,
        "Convert": 0.7,
        "Cost": 10,
        "Customer_ID":10
      }
    ]
  }
}

我正在嘗試檢索特定 customer_ID 的價格我正在使用此查詢來獲取 Customer_ID=1 的價格

select json_array_elements(t.info -> 'data' -> 'results') ->> 'price'
from mytable  t
where exists (
    select 
    from json_array_elements(t.info -> 'data' -> 'results') x(elt)
    where (x.elt ->> 'Customer_ID')::int = 1
)

問題是我得到了相同的結果 Customer_ID=1 和 Customer_ID=10 我基本上得到了數組的兩個元素而不是一個。 我不知道我做錯了什么

您可以使用橫向連接來取消嵌套數組元素,然后使用where子句過濾客戶; 這讓您只剩下一行,您可以從中提取價格:

select x.elt ->> 'price' price
from mytable t 
cross join lateral json_array_elements(t.info -> 'data' -> 'results') x(elt)
where x.elt ->> 'Customer_ID' = 1

請注意,您不需要將客戶 ID 轉換為int ,因為它已經以正確的格式存儲在 json 數組中。

暫無
暫無

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

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