sql - postgresql 在 where 子句中使用 json 子元素

标签 sql json database postgresql postgresql-9.3

这可能是一个非常基本的问题,但我无法在网上找到任何内容。

如果我创建一个示例表:

 create table dummy ( id int not null, data json );

然后,如果我使用以下查询查询表:

select * from dummy where data->'x' = 10;

现在,由于表中还没有记录,并且任何记录中都没有“x”这样的属性,因此它应该返回零结果。

但是我得到以下错误:

postgres=# select * from dummy where data->'x' = 10;
ERROR:  operator does not exist: json = integer
LINE 1: select * from dummy where data->'x' = 10;

但是以下查询有效:

select * from dummy where cast(data->>'x' as integer) = 10;

我是不是遗漏了什么,或者类型转换是我从 json 字段中获取整数值的唯一方法?如果是这样,当数据变得非常大时,它不会影响性能吗?

最佳答案

Am I missing something here or typecasting is the only way I can get an integer value from a json field ?

你是对的,类型转换是从 json 字段中读取整数值的唯一方法。

If that's the case, does it not affect the performance when data becomes extremely large ?

Postgres 允许您索引包括转换在内的函数,因此下面的索引将允许您快速检索所有 data->>x 具有某个整数值的行

CREATE INDEX dummy_x_idx ON dummy(cast("data"->>'x' AS int))

关于sql - postgresql 在 where 子句中使用 json 子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24043688/

相关文章:

php - 导入大型数据集的性能提示

ruby-on-rails - Rails 2.3 App 运行数据库迁移问题

mysql - 获取数据库中最近的位置

json - 请帮我弄清楚如何解析这个json文件

mysql - MySQL 查询中的复杂 WHERE 子句 - [在 MySQL 中使用 VLOOKUP]

sql - Snowflake 中有等效的 jsonb_array_elements 吗?

sql - SQL 语法中的 LAG 和 LEAD 替代方案

mysql - 当我在 MySQL 中创建数据库时,我的数据库保存在哪里?

mysql - 使用 JOINS 而不是子查询

mysql - COALESCE(FIELD, "DEFAULT VALUE") 不适用于 postgresql + rails