我在表中有一个json字段(存储为文本),我想从json中提取嵌套数组中指定ID的某些项(在json中)。
每个json项都有type
属性和value
属性。 value
还有一个GRI
属性(数组),我想用它来过滤。以下是一个流场列项的示例:
[{"type": "paragraph",
"value": {"paragraph": "<p>Sample paragraph 91</p>", "GRI": [27, 91, 211]},
{"type": "paragraph",
"value": {"paragraph": "<p>Sample paragraph 191</p>", "GRI": [13, 191, 271]}]
此查询有效:
SELECT value FROM "sampletable" r, json_array_elements(r.streamfield::json) obj
WHERE obj->>'type' = 'paragraph' AND obj#>>'{value,GRI}' LIKE '%91%';
这会给我所有ID为91的物品。但也有ID 191,291等......
那么如何将`obj#&gt;&gt;'{value,GRI}'语句转换为数组,以便我可以根据指定的ID进行过滤?
这是一个SQLFiddle:http://sqlfiddle.com/#!15/184e1/1
编辑:澄清JSON的结构
答案 0 :(得分:0)
在这里,我将如何处理这个问题。基本上,您需要将JSON数组的项目作为一个集合返回,然后从中创建一个PostgreSQL数组。
DROP TABLE IF EXISTS "sampletable";
CREATE TEMP TABLE "sampletable" (streamfield TEXT);
INSERT INTO "sampletable" VALUES ('{"type": "paragraph", "value": {"paragraph": "<p>Sample paragraph 91</p>", "GRI": [27, 91, 211]}}');
-- Easier to separate out in a CTE, but this could be a subquery, if need be.
WITH cte AS
(
SELECT
(streamfield::JSON)->>'type' AS type_text,
JSON_EXTRACT_PATH_TEXT(streamfield::JSON,'value','paragraph') AS paragraph_text,
(SELECT ARRAY_AGG(col::INT) FROM JSON_ARRAY_ELEMENTS_TEXT(JSON_EXTRACT_PATH(streamfield::JSON,'value','GRI')) tbl(col)) AS gri_array -- This is an INT array now
FROM
"sampletable"
)
SELECT
type_text,
paragraph_text,
gri_array
FROM
cte
WHERE
type_text = 'paragraph' AND
91 = ANY(gri_array)