从 SQL 中类似字典的列中查询单个元素
Query a single element from a dictionary-like column in SQL
我有一个 PostgresSQL table,如下所示:
id order_id products
[PK] integer integer character varying
1 123 {"type": "foo", "counts": 2}
2 456 {"type": "foobar", "counts": 4}
3 789 {"type": "foo", "counts": 1}
4 678 {"type": "baz", "counts": 3}
我只想查询 type = foo
.
在另一个查询中,我成功地使用了以下内容:
SELECT
table_a.data::json->>'type' prod_type,
FROM table.a
但是,这只有效,因为 data
列是 JSON 类型。
我如何索引到 products
列,以便我只 return type = foo
?
1 123 {"type": "foo", "counts": 2}
3 789 {"type": "foo", "counts": 1}
谢谢!
您可以尝试这样的操作:
SELECT *
FROM test
WHERE products::json->>'type' = 'foo';
示例输出:
我有一个 PostgresSQL table,如下所示:
id order_id products
[PK] integer integer character varying
1 123 {"type": "foo", "counts": 2}
2 456 {"type": "foobar", "counts": 4}
3 789 {"type": "foo", "counts": 1}
4 678 {"type": "baz", "counts": 3}
我只想查询 type = foo
.
在另一个查询中,我成功地使用了以下内容:
SELECT
table_a.data::json->>'type' prod_type,
FROM table.a
但是,这只有效,因为 data
列是 JSON 类型。
我如何索引到 products
列,以便我只 return type = foo
?
1 123 {"type": "foo", "counts": 2}
3 789 {"type": "foo", "counts": 1}
谢谢!
您可以尝试这样的操作:
SELECT *
FROM test
WHERE products::json->>'type' = 'foo';
示例输出: