查询jsonb数据满足一定条件的列
Query a column with jsonb data meeting certain criteria
问题
我有一个 table 这样的:
product
tags (jsonb)
P001
[{"name": "LX","active": true}, {"name": "TX","active": true}]
P002
[{"name": "LX","active": true}]
我正在尝试查询此 table 以获取具有相同标签的产品列表。
我发现以下内容不足以满足我的查询要求,因为它会匹配至少具有我查询的标签的所有产品:
SELECT product
FROM product_table
WHERE tags @> '[
{"name": "LX","active": true}
]';
结果
product
P001
P002
所以我需要更精确的匹配,而不是严格到要求数组中标记对象的顺序。例如:
[
{
"name": "LX",
"active": true
},
{
"name": "TX",
"active": true
}
]
-- Interpreted the same as
[
{
"name": "TX",
"active": true
},
{
"name": "LX",
"active": true
}
]
想要的结果
仅与查询中的标签匹配的产品列表。
资源
我用来尝试解决问题的资源列表。
根据你给出的例子,你可以在两个方向上同时使用遏制。
...WHERE tags <@ :whatever and tags @> :whatever
如果您不喜欢重复参数,您可以创建自定义函数或运算符:
create function equal_but_for_order(jsonb,jsonb) returns boolean language sql as $$
select <@ and @>
$$;
create operator <@> (function = equal_but_for_order, leftarg = jsonb, rightarg=jsonb);
...WHERE tags <@> :whatever
问题
我有一个 table 这样的:
product | tags (jsonb) |
---|---|
P001 | [{"name": "LX","active": true}, {"name": "TX","active": true}] |
P002 | [{"name": "LX","active": true}] |
我正在尝试查询此 table 以获取具有相同标签的产品列表。
我发现以下内容不足以满足我的查询要求,因为它会匹配至少具有我查询的标签的所有产品:
SELECT product
FROM product_table
WHERE tags @> '[
{"name": "LX","active": true}
]';
结果
product |
---|
P001 |
P002 |
所以我需要更精确的匹配,而不是严格到要求数组中标记对象的顺序。例如:
[
{
"name": "LX",
"active": true
},
{
"name": "TX",
"active": true
}
]
-- Interpreted the same as
[
{
"name": "TX",
"active": true
},
{
"name": "LX",
"active": true
}
]
想要的结果
仅与查询中的标签匹配的产品列表。
资源
我用来尝试解决问题的资源列表。
根据你给出的例子,你可以在两个方向上同时使用遏制。
...WHERE tags <@ :whatever and tags @> :whatever
如果您不喜欢重复参数,您可以创建自定义函数或运算符:
create function equal_but_for_order(jsonb,jsonb) returns boolean language sql as $$
select <@ and @>
$$;
create operator <@> (function = equal_but_for_order, leftarg = jsonb, rightarg=jsonb);
...WHERE tags <@> :whatever