sql - 在 postgres json 字段中查询 json 键

标签 sql json postgresql postgresql-9.2

假设我在 Postgres 中像这样存储在名为“数据”的 JSON 字段中

{
    "CUSTA": {
        "name": "Customer A",
    },
    "CUSTB": {
        "name": "Customer B",
    },
    "CUSTC": {
        "name": "Customer C",
    }
}

如何查询返回包含键“CUSTA”的记录?甚至更好的“CUSTA”的值是“name”:“Customer A”

尝试做这样的事情,但显然我不能使用关键字 key

SELECT * FROM invoices WHERE data->>key = 'CUSTA';

最佳答案

select '{
    "CUSTA": {
        "name": "Customer A"
    },
    "CUSTB": {
        "name": "Customer B"
    },
    "CUSTC": {
        "name": "Customer C"
    }
}'::json#>>'{CUSTA}';
           ?column?
------------------------------
 {                           +
         "name": "Customer A"+
     }
(1 row)

注意:name:customer x 后有尾随逗号,这不是正确的 json。对于您的查询,您可能会执行以下操作:

select data#>>'{CUSTA}' from invoices;

或者,如果数据还不是 json 字段:

select data::json#>>'{CUSTA}' from invoices;

我不明白为什么一张发票会有多个客户。

-g

关于sql - 在 postgres json 字段中查询 json 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23697540/

相关文章:

php - 如何在查询中连接

Python 和 PostgreSQL

mysql - utf8_turkish_ci 归类上的 MySql LIKE 运算符有什么问题?

mysql - 缺少 NULL 答案的 SQL JOIN 问题和答案

javascript - JSON Javascript 解析字符串

json - Jersey 在添加 jersey-* 依赖项时不存在 WebApplication 提供程序

sql - 从 postgresql DB 中的 jsonb 列检索数据作为数组,返回空结果

postgresql - 为什么 psql 不能识别我的单引号?

mysql - 选择一个项目,该项目在数据库中重复出现的总次数以及该项目状态为1的次数

python - 解析Json文件并保存特定值