postgres json_b 数组不包含部分对象

问题描述 投票:0回答:1

给定一个名为

attributes
的 json_b 数组列,其中包含多个 json 对象。我如何查询
attributes
列以获取该列中任何 json 对象中没有特定值的所有行。

例如,给定以下 4 行

[{"one": 1}, {"two":2}, {"three": 3, "foo": "foo", "baz": "baz"}]
[{"one": 1}, {"three": 3, "foo": "foo" }]
[{"foo": "foo" }]
[{"one": 1}, {"two":2}, {"three": 3, "baz": "baz"}]

我想获取数组中任何对象中没有

"foo": "foo"
的所有行。在上面的示例中,应返回最后一行。

可以将数组转换为文本,然后使用

like
运算符来匹配字符串,但这很容易出错,并且由于转换为文本,可能会运行更长时间。

postgresql jsonb
1个回答
0
投票

您可以使用 JSONB_ARRAY_ELEMENTS 函数取消“attributes”数组列中 JSON 对象的嵌套,然后进行过滤。试试这个:

CREATE TABLE my_table (
    id SERIAL PRIMARY KEY,
    attributes JSONB
);

--Sample data
INSERT INTO my_table (attributes) VALUES
('[{"one": 1}, {"two":2}, {"three": 3, "foo": "foo", "baz": "baz"}]'),
('[{"one": 1}, {"three": 3, "foo": "foo" }]'),
('[{"foo": "foo" }]'),
('[{"one": 1}, {"two":2}, {"three": 3, "baz": "baz"}]');

SELECT *
FROM my_table
WHERE NOT EXISTS (
  SELECT 1
  FROM JSONB_ARRAY_ELEMENTS(attributes) AS elem
  WHERE elem->>'foo' = 'foo'
);

我已将虚拟数据添加到表中并尝试查询,它按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.