POSTGRESQL 从 jsonb 中提取密钥
Posted
技术标签:
【中文标题】POSTGRESQL 从 jsonb 中提取密钥【英文标题】:POSTGRESQL extract keys from jsonb 【发布时间】:2021-07-07 13:22:32 【问题描述】:我有一个包含大量外部数据的 jsonb 列的表,我需要提取一些键,但我很难做到。
桌子是这样的:
代码标题 external_data G20540 数据分析
外部数据是 jsonb 列,在数组中用 dict 组织,它有以下信息:
[
"DESCR": "Requisito RJ_GRD_GCSOSRJ",
"ORDERNO": "10",
"ACAD_PLAN": "",
"ACAD_PROG": "",
"DESCR254A": "Requisito RJ_GRD_GCSOSRJ_Plan. de Comunicação I",
"DESCRSHORT": "Requisito",
"EFF_STATUS": "A",
"RQ_CONNECT": "",
"ACAD_CAREER": "",
"INSTITUTION": "X",
"PARENTHESIS": "",
"SAA_DESCR80": "Requisito RJ_GRD_GCSOSRJ_Plan. de Comunicação I",
"RQRMNT_GROUP": "000312",
"ACAD_SUB_PLAN": "",
"CREATION_DATE": "2020-04-13T21:26:51.923",
"RQRMNT_USEAGE": "ENR",
"CONDITION_CODE": "CRS",
"CONDITION_DATA": "003130",
"REQUISITE_TYPE": "PRE",
"CONDITION_DESCR": "ID Curso",
"RQRMNT_LIST_SEQ": "1",
"RQ_GRP_LINE_NBR": "0010",
"RQ_LINE_KEY_NBR": "0001",
"RQ_GRP_LINE_TYPE": "CRSE",
"CONDITION_OPERATOR": "EQ"
]
我需要提取“DESCR”、“ORDENO”、“DESCR254A”、“SAA_DESCR80”、“RQRMNT_GROUP”、“RQRMNT_USEAGE”、“EFF_STATUS”。
我尝试了这个查询,但我只得到了 external_data 列的空结果:
SELECT codes.external_id as "code"
,codes.title as "title"
,requirements.external_data ->> 'RQRMNT_GROUP' as "RQRMNT_GROUP"
,requirements.external_data ->> 'EFF_STATUS' as "EFF_STATUS"
,requirements.external_data ->> 'RQRMNT_USEAGE' as "RQRMNT_USEAGE"
,requirements.external_data ->> 'DESCR' as "DESCR"
,requirements.external_data ->> 'SAA_DESCR80' as "SAA_DESCR80"
,requirements.external_data ->> 'DESCR254A' as "DESCR254A"
,requirements.external_data ->> 'ORDERNO' as "ORDERNO"
FROM requirements
LEFT JOIN codes ON codes.id = requirements.code_id
我该怎么做?
【问题讨论】:
您的 JSON 值是一个数组。您需要使用-> 0 ->> 'RQRMNT_GROUP'
来访问第一个数组元素。如果数组包含多个元素,你想要什么结果
谢谢!成功了!
【参考方案1】:
您需要使用WITH
子句来识别数组中的表并从中进行选择:
WITH external_codes AS (
SELECT r.code_id,
jsonb_array_elements(r.external_data) AS external_data
FROM requirements r
)
SELECT codes.external_id as "code"
,codes.title as "title"
,external_codes.external_data ->> 'RQRMNT_GROUP' as "RQRMNT_GROUP"
,external_codes.external_data ->> 'EFF_STATUS' as "EFF_STATUS"
,external_codes.external_data ->> 'RQRMNT_USEAGE' as "RQRMNT_USEAGE"
,external_codes.external_data ->> 'DESCR' as "DESCR"
,external_codes.external_data ->> 'SAA_DESCR80' as "SAA_DESCR80"
,external_codes.external_data ->> 'DESCR254A' as "DESCR254A"
,external_codes.external_data ->> 'ORDERNO' as "ORDERNO"
FROM external_codes
LEFT JOIN codes ON codes.id = external_codes.code_id
【讨论】:
以上是关于POSTGRESQL 从 jsonb 中提取密钥的主要内容,如果未能解决你的问题,请参考以下文章
如何从 PostgreSQL 中的 JSONB 数组中获取特定对象的值?
PostgreSQL9.4往jsonb字段新增键值SQL怎么写