Postgresq 9.6
json
"availability": [
{
"qty": 25,
"price": 1599,
"is_available": true
},
{
"qty": 72,
"price": 3599,
},
"is_available": true
]
具有数据列的表格。类型为 jsonb
如果我想按“ 价格”字段对第一个数组的(可用性)项目进行排序,我会这样:
SELECT *
from product prod
WHERE to_tsvector('english', prod.data) @@ to_tsquery('gram')
ORDER BY prod.data #> '{availability,0,price}' desc
好。
但是我需要在数组可用性
中对所有字段“ 价格”进行排序这样的SMT(伪代码)
SELECT *
from product prod
WHERE to_tsvector('english', prod.data) @@ to_tsquery('gram')
ORDER BY prod.data #> '{availability,*,price}' desc
我需要按“价格”描述进行订购。
结果必须是
结果的第一条记录是第二个json
"availability": [
{
"qty": 25,
"price": 11599,
"is_available": true
},
{
"qty": 72,
"price": 13599,
},
"is_available": true
]
...
"availability": [
{
"qty": 25,
"price": 1599,
"is_available": true
},
{
"qty": 72,
"price": 3599,
},
"is_available": true
]
有可能吗?
答案 0 :(得分:1)
可以这样做:
select id,
jsonb_set(data, '{availability}',
(select jsonb_agg(item order by (item ->> 'price')::numeric)
from jsonb_array_elements(data -> 'availability') as x(item))
) as data
from product
where ...