微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

如果我创建一个示例表:

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))

原文地址:https://www.jb51.cc/postgresql/191775.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐