json - PostgreSQL JSON 类型和查询

标签 json postgresql

使用 PostgreSQL 9.4,是否可以使用比较运算符在 JSON 数据类型中查找数值(例如,给我所有记录,其中 JSON 列中的年龄属性优于 18)?

CREATE TABLE data
(
   id serial NOT NULL,
   attributes jsonb
);

INSERT INTO data (id, attributes) VALUES (1, '{"name": "Value A", "value": 20}');
INSERT INTO data (id, attributes) VALUES (2, '{"name": "Value B", "value": 10}');

我想知道如何查询此表以获取“值”属性优于 18 的所有记录

在当前情况下,id 为 1 的记录将是唯一的结果。

相等性有效(但它是字符串比较):

SELECT *  from data WHERE attributes->>'value' = '10';

如何处理数字?

SELECT *  from data WHERE attributes->>'value' > 18;
 ==> ERROR: operator does not exist: text > integer

SELECT *  from data WHERE attributes->>'value'::integer > 18;
 ==> ERROR: invalid input syntax for integer: "value"

谢谢。

最佳答案

:: 转换运算符在求值优先级上几乎高于任何其他运算符(. 除外),因此您需要添加括号:

SELECT *  from data WHERE (attributes->>'value')::integer > 18;

符合标准的替代方案:

 SELECT *  from data WHERE cast(attributes->>'value' AS integer) > 18;

关于json - PostgreSQL JSON 类型和查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27817613/

相关文章:

java - avro union的json编码

php - 通过命令行或 PHP 以 json 格式导出 mysql 数据库/mysql 表

sql - 在 PostgreSQL 8.0 中获取最大值

sql - 在 SQL 中使用破折号 (-) 和空格分隔的搜索值的简便方法

php - 解析带有可选微秒时区的 postgres 日期时间

postgresql - 为什么我的表达式索引不接受与查询相同的语法?

php - MySQL SELECT WHERE 多个值

ios - 如果 JSON 响应是 "true",不在 TableView 中显示结果

javascript - 按多个匹配值过滤数组

c - 使用 C 扩展在 Postgres DB 中存储带有时区的时间戳?