PostgreSQL - jsonb_each

Ala*_*gan 12 postgresql jsonb

我刚刚开始在postgres上玩jsonb并找到难以在网上找到的例子,因为它是一个相对较新的概念.我正在尝试使用jsonb_each_text打印出一个键和值表,但在一个列中得到一个csv.

我将以下json保存为jsonb并使用它来测试我的查询.

{
  "lookup_id": "730fca0c-2984-4d5c-8fab-2a9aa2144534",
  "service_type": "XXX",
  "metadata": "sampledata2",
  "matrix": [
    {
        "payment_selection": "type",
        "offer_currencies": [
            {
              "currency_code": "EUR",
              "value": 1220.42
            }
        ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我可以访问offer_currencies数组

SELECT element -> 'offer_currencies' -> 0
FROM test t, jsonb_array_elements(t.json -> 'matrix') AS element
WHERE element ->> 'payment_selection' = 'type'
Run Code Online (Sandbox Code Playgroud)

给出"{"值":1220.42,"currency_code":"EUR"}"的结果,所以如果我运行以下查询我得到(我必须更改"for")

select * from jsonb_each_text('{"value": 1220.42, "currency_code": "EUR"}')

Key            | Value
---------------|----------
"value"        | "1220.42"
"currency_code"| "EUR"
Run Code Online (Sandbox Code Playgroud)

所以使用上面的理论我创建了这个查询

SELECT jsonb_each_text(data)
FROM (SELECT element -> 'offer_currencies' -> 0 AS data
  FROM test t, jsonb_array_elements(t.json -> 'matrix') AS element
  WHERE element ->> 'payment_selection' = 'type') AS dummy;
Run Code Online (Sandbox Code Playgroud)

但这会在一列中打印出csv

record
---------------------
"(value,1220.42)"
"(currency_code,EUR)"
Run Code Online (Sandbox Code Playgroud)

poz*_*ozs 24

这里的主要问题是你选择整行作为一列(PostgreSQL允许).你可以解决这个问题SELECT (jsonb_each_text(data)).* ....

但是:不要SELECT设置返回函数,这通常会导致错误(或意外结果).相反,使用f.ex. LATERAL加入/子查询:

select first_currency.*
from   test t
     , jsonb_array_elements(t.json -> 'matrix') element
     , jsonb_each_text(element -> 'offer_currencies' -> 0) first_currency
where  element ->> 'payment_selection' = 'type'
Run Code Online (Sandbox Code Playgroud)

注意:FROM子句中的函数调用是隐式LATERAL连接(此处:CROSS JOINs).

  • 你能推荐任何资源来学习这样的习语("不要选择设置返回功能,这通常会导致错误")? (7认同)