这可能是一个非常基本的问题,但我无法在网上找到任何内容。
如果我创建一个示例表:
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/