所以這是我的 Postgres 資料庫中的 JSON 列:
{
"objekt_art": {
"86": {
"code": "86",
"bezeichnung_de": "Kino",
"bezeichnung_fr": "Cinéma",
"bezeichnung_it": "Cinema",
"bezeichnung_en": null,
"kurz_bezeichnung_de": "Kino",
"relevant_fuer_berechnung_steuerquote": true
},
"27": {
"code": "27",
"bezeichnung_de": "Kiosk",
"bezeichnung_fr": "Kiosque",
"bezeichnung_it": "Chiosco",
"bezeichnung_en": null,
"kurz_bezeichnung_de": "Kiosk",
"relevant_fuer_berechnung_steuerquote": true
}
}
}
我需要能夠查詢 bezechnung_de 例如其中代碼 = 86。我可以從另一個表傳遞的代碼數量。
例如,我如何使用兩列進行查詢。一個是數字,第二個是 bezeichnung_de。
像這樣:
Code Bez
86 Kino
uj5u.com熱心網友回復:
連接資料的示例資料結構和示例表:dbfiddle
select
je.value -> 'code' as "Code",
je.value -> 'bezeichnung_de' as "Bez"
from
test t
cross join jsonb_each((data::jsonb ->> 'objekt_art')::jsonb) je
-- In table test_join I insert value 86 for join record
inner join test_join tj on je.key::int = tj.json_id
uj5u.com熱心網友回復:
如您所知,這很容易:
select t.the_column -> 'objekt_art' -> '86' ->> 'code' as code,
t.the_column -> 'objekt_art' -> '86' ->> 'bezeichnung_de' as bez
from the_table t
where ...
該值'86'可以是一個引數。不過,選擇代碼的第一個運算式并不是真正需要的,因為您可以直接將其替換為常量值(= 引數)。
如果“外部”JSON 鍵的值與該code值不同,您可以使用以下內容:
select o.value ->> 'code' as code,
o.value ->> 'bezeichnung_de' as bez
from the_table t
cross join jsonb_each(t.the_column -> 'objekt_art') o(key, value)
where o.key = '86'
and ... other conditions ...
如果您使用的是 Postgres 13 或更高版本,這也可以寫成 JSON 路徑運算式:
select a.item ->> 'code' as code,
a.item ->> 'bezeichnung_de' as bez
from (
select jsonb_path_query_first(t.the_column, '$.objekt_art.* ? (@.code == "86")') as item
from the_table t
where ....
) a
所有示例都假定列是用jsonb它應該是的資料定義的。如果不是,則需要投射它:the_column::jsonb
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346598.html
標籤:json PostgreSQL 目的
上一篇:使用特定格式的特征標記文本
