任何人都可以帮我搜索Postgres数据库的json数据类型。
我有一个表transactions
并且包含以下类似值数组:
column: "data" datatype: json
单一演示交易:
{
"id": "tran_54645bcb98ba7acfe204",
"amount": 4200,
...
"fees": [
{
"type": "application",
"application": "app_1d70acbf80c8c35ce83680715c06be0d15c06be0d",
"payment": "pay_917018675b21ca03c4fb",
"amount": 420,
"currency": "EUR",
"billed_at": null
}
]
}
嵌套交易清单:
[
{
"id": "tran_54645bcb98ba7acfe204",
"amount": 4200,
"fees": [
{
"type": "application",
"application": "app_1d70acbf80c8c35ce83680715c06be0d15c06be0d",
"payment": "pay_917018675b21ca03c4fb",
"amount": 420,
"currency": "EUR",
"billed_at": null
}
]
},
{
"id": "tran_98645bcb98ba7acfe204",
"amount": 4200,
"fees": [
{
"type": "application",
"application": "app_1d70acbf80c8c35ce83680715c06be0d15c06be0d",
"payment": "pay_917018675b21ca03c4fb",
"amount": 120,
"currency": "AUD",
"billed_at": null
}
]
}
]
如果我希望获得amount > 300
以及currency = EUR
的所有交易,我将如何获得这些交易?
我是Postgres的新手,所以需要帮助理解Postgres nosql的查询构建,特别是PHP
答案 0 :(得分:4)
仅适用于嵌套JSON数组中的单个元素:
SELECT *
FROM transactions
WHERE (data #>> '{fees,0,amount}')::numeric > '300'
AND (data #>> '{fees,0,currency}') = 'EUR';
对于具有更多元素的数组,您需要做更多 有关JSON Functions and Operators。
的手册由于您使用的是Postgres 9.4:使用jsonb
会有更好的选项,特别是对于多个数组元素:
要在评论中获得您要求的金额:
SELECT sum((data #>> '{fees,0,amount}')::numeric) AS sum_amount
FROM ...