Oracle JSON_表到PostgreSQL-如何从JSON列中的第二个分层键进行搜索
我正在尝试将Oracle 12c查询迁移到Postgres11.5 以下是json:Oracle JSON_表到PostgreSQL-如何从JSON列中的第二个分层键进行搜索,json,oracle,postgresql,database-migration,jsonb,Json,Oracle,Postgresql,Database Migration,Jsonb,我正在尝试将Oracle 12c查询迁移到Postgres11.5 以下是json: { "cost": [{ "spent": [{ "ID": "HR", "spentamount": { "amount": 2000.0, "country": "US" } }] }], "time": [{ "spent": [{ "ID": "HR", "spentamou
{
"cost": [{
"spent": [{
"ID": "HR",
"spentamount": {
"amount": 2000.0,
"country": "US"
}
}]
}],
"time": [{
"spent": [{
"ID": "HR",
"spentamount": {
"amount": 308.91,
"country": "US"
}
}]
}]
}
以下是必须迁移到Postgres 11.5的查询:
select js.*
from P_P_J r,
json_table(r.P_D_J, '$.*[*]'
COLUMNS(NESTED PATH '$.spent[*]'
COLUMNS(
ID VARCHAR2(100 CHAR) PATH '$.ID',
amount NUMBER(10,4) PATH '$.spentamount.amount',
country VARCHAR2(100 CHAR) PATH '$.spentamount.country'))
) js
结果是:
ID, amount, country
HR, 2000.0,US
HR,308.91,US
我这里有两个问题:
$.[*]
是什么意思Postgres中没有json_表的直接替换。您必须组合几个调用来分解JSON结构 您没有向我们展示您的预期输出,但据我所知,以下内容也应如此:
select e.item ->> 'ID' as id,
(e.item #>> '{spentamount, amount}')::numeric as amount,
e.item #>> '{spentamount, country}' as country
from p_p_j r
cross join jsonb_each(r.p_d_j) as a(key, val)
cross join lateral (
select *
from jsonb_array_elements(a.val)
where jsonb_typeof(a.val) = 'array'
) as s(element)
cross join jsonb_array_elements(s.element -> 'spent') as e(item)
;
JSON路径表达式'$.[*]
的意思是:迭代所有顶级键,然后迭代在其中找到的所有数组元素,嵌套路径'$.spend[*]'
然后再次迭代其中的所有数组元素。这些步骤反映在三个JSON函数调用中,这三个函数调用是实现这些步骤所必需的
对于Postgres 12,这将更容易一些,因为只需调用
jsonb_path_query()
,也可以使用JSON路径访问元素,使用非常类似的JSON路径表达式:
select e.item ->> 'ID' as id,
(e.item #>> '{spentamount, amount}')::numeric as amount,
e.item #>> '{spentamount, country}' as country
from p_p_j r
cross join jsonb_path_query(r.p_d_j, '$.*[*].spent[*]') as e(item)
;
@AnuC如果该答案解决了您的问题,请将其删除,以便您的问题标记为已解决。