我在從 json 欄位查詢資料時遇到問題。
我在我的 postgres 資料庫(版本 10)中有一些 json 格式的列保存為文本
有時我需要能夠在 json 值上連接兩個表。
我不知道我怎么能做到這一點..
這是一個簡單的例子。
在我的選擇中,我想輸出水果和顏色。
我在水果表的 json 中有 color_cd 編號,我可以在 code_table 的另一個 json 中找到顏色。
我希望的輸出應該是這樣的
Fruit_ID Name Color
1000 Pear Green
1001 Banana Yellow
小提琴鏈接 --> https://dbfiddle.uk/?rdbms=postgres_13&fiddle=3f989db0524e288183619bab63fc9add
uj5u.com熱心網友回復:
您records在表code_table上的列在 json 資料中存在問題,我修復了問題并更改為以下格式:
{"color_cd":{"30":{"code":"30","color":"yellow"},"55":{"code":"55","color":"green"},"60":{"code":"60","color":"red"}}}
您可以在dbfiddle 中看到查詢結構和結果
select
f.id,
f.name,
j_cd.value ->> 'color' as color
from
code_table ct
cross join jsonb_each(records::jsonb -> 'color_cd') j_cd
inner join fruits f on f.type_cd :: jsonb ->> 'color_cd' = j_cd.key::text
where
ct.name = 'color_cd'
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334029.html
標籤:json PostgreSQL 加入
