arrays - Postgres 9.4 按 json 数组的元素值选择

标签 arrays json postgresql jsonb postgresql-9.4

有一个 'accounts' 表,其中 'data'::jsonb 字段填充:

{
    "cars": [{"body": "E-JZA80-ALFQZ", 
         "year": 1999, 
         "brand": "Toyota", 
         "model": "Vista Ardeo"} 
     ], 
    "name": "Gilbert Moore", 
    "phone": "+13222314555"
}

我正在尝试类似的东西: select * from accounts where data->'cars' @> '{"brand":"Toyota"}' 但它不显示记录。错过了什么?

最佳答案

您的查询需要以下形式的 json 值:

{
    "cars": {"body": "E-JZA80-ALFQZ", 
         "year": 1999, 
         "brand": "Toyota", 
         "model": "Vista Ardeo"} 
     , 
    "name": "Gilbert Moore", 
    "phone": "+13222314555"
}

但是在实际数据中data->'cars'是一个数组,不是一个对象,所以查询应该是:

select a.*
from accounts a
where data->'cars' @> '[{"brand":"Toyota"}]'

as operator @> 适用于两个对象或两个数组。

关于arrays - Postgres 9.4 按 json 数组的元素值选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31764901/

相关文章:

c - C语言中如何返回一个数组?

postgresql - 使用 PL/pgSQL 检查 JSON 中是否存在 key ?

java - PostgreSQL 异常 : org. postgresql.util.PSQLException:发送到后端时发生 I/O 错误

php - 有没有办法将数组转换为类属性?

c - 这个程序中的段错误是什么

algorithm - 数组去除重复元素

php - JQuery.ajax 和对象和 php 的空响应

json - 在 BASH 中从 URL 获取 JSON 值

PostgreSQL 9.4 突然无效的内存分配请求大小

postgresql - Adminer & Migrate 无法连接到 Postgresql Docker 容器