如何遍历 JSON 个对象的 JSON 数组以查看它是否包含我在 postgres 中查找的值?

How to loop through JSON array of JSON objects to see if it contains a value that I am looking for in postgres?

这里是 json 对象的例子

rawJSON = [
   {"a":0, "b":7},
   {"a":1, "b":8}, 
   {"a":2, "b":9}
]

我有一个 table 基本上看起来像这样。

demo Table

id | ...(other columns)      | rawJSON
------------------------------------
0  | ...(other columns info) | [{"a":0, "b":7},{"a":1, "b":8}, {"a":2, "b":9}]
1  | ...(other columns info) | [{"a":0, "b":17},{"a":11, "b":5}, {"a":12, "b":5}]

我想要的是 return insideRawJSON 的行 "a" 的值小于 2 并且 "b" 的值小于 8。它们必须来自同一个 JSON 对象。

查询本质上类似这样

SELECT *
FROM demo
WHERE FOR ANY JSON OBJECT in rawJSON column -> "a" < 2 AND -> "b" < 8

因此它将 return

id | ...(other columns)      | rawJSON
------------------------------------
0  | ...(other columns info) | [{"a":0, "b":7},{"a":1, "b":8}, {"a":2, "b":9}]

我已经从这里的几个帖子中进行了搜索,但无法弄清楚。 https://dba.stackexchange.com/questions/229069/extract-json-array-of-numbers-from-json-array-of-objects https://dba.stackexchange.com/questions/54283/how-to-turn-json-array-into-postgres-array

我正在考虑创建一个 plgpsql 函数,但无法弄清楚。

如有任何建议,我将不胜感激!

谢谢!!

我想避免横向交叉连接,因为它会减慢很多。

您可以使用子查询来搜索数组元素以及 EXISTS

SELECT *
       FROM demo d
       WHERE EXISTS (SELECT *
                            FROM jsonb_array_elements(d.rawjson) a(e)
                            WHERE (a.e->>'a')::integer < 2
                                  AND (a.e->>'b')::integer < 8);

db<>fiddle

如果 rawjson 的数据类型是 json 而不是 jsonb,请使用 json_array_elements() 而不是 jsonb_array_elements()