1

有一个 '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"}' 但它没有显示记录。错过了什么?

4

1 回答 1

1

您的查询需要以下形式的 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 运算符 @> 适用于两个对象或两个数组。

于 2015-08-01T21:56:14.973 回答