假设我在 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/