有一个 '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/