gpt4 book ai didi

json - PostgreSQL JSON 类型和查询

转载 作者:行者123 更新时间:2023-11-29 11:43:11 24 4
gpt4 key购买 nike

使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com