我想过滤带有gold
徽章的行。我正在使用PG12,我使用它的新路径功能。
为了澄清,我有一张这样的表格:
CREATE TABLE users_tbl (
ID serial NOT NULL PRIMARY KEY,
data jsonb NOT NULL
);
并允许插入值:
INSERT INTO users_tbl (ID, data) values (1, '{"badges": ["gold", "silver"], "another_field": 1}');
INSERT INTO users_tbl (ID, data) values (2, '{"badges": ["silver"], "another_field": 3}');
INSERT INTO users_tbl (ID, data) values (3, '{"badges": ["gold"], "another_field": 4}');
现在,当我这样查询时:
SELECT
ID, jsonb_path_query("data", '$.badges') AS "badges"
FROM "users_tbl";
我得到了预期的以下结果:
+----+--------------------+
+ ID | badges +
+----+--------------------+
+ 1 | ["gold", "silver"] +
+----+--------------------+
+ 2 | ["silver"] +
+----+--------------------+
+ 3 | ["gold"] +
+----+--------------------+
现在列表只有
users_tbl
个匹配项badge
SELECT
jsonb_path_query("data", '$.badges') AS "badges"
FROM "users_tbl"
WHERE "badges" @> 'gold';
预期结果:
+----+--------------------+
+ ID | badges +
+----+--------------------+
+ 1 | ["gold", "silver"] +
+----+--------------------+
+ 3 | ["gold"] +
+----+--------------------+
实际结果:
column "badges" does not exist
如何针对
gold
添加条件?还是我做了不正确的事?我怎样才能在我的情况下得到预期的结果?注:PostgreSQL 12。
更新:
实际上在这个例子中,我使用了一个简单的jsonb对象。实际上是这样的:
{
"properties": {
"badges": ["gold", "silver"]
}
}
所以,
badges
在badges
最佳答案
可以使用包含运算符:
select
jsonb_path_query(data, '$.badges') as badges
from users_tbl
where data->'badges' @> '"gold"';
或
jsonb_path_exists()
:select
jsonb_path_query(data, '$.badges') as badges
from users_tbl
where jsonb_path_exists(data, '$.badges ? (@[*] == "gold")')