如何解决查找价格高于使用JSON运算符
Json:
"availability": [
{
"qty": 25,"price": 3599,"is_available": true
},{
"qty": 72,},"is_available": true
]
如果我要查找值为=“ 3599 ”的价格,请使用以下查询:
select *
from product
where to_tsvector(product.data #>> '{availability}') @@ to_tsquery('3599')
或此查询:
SELECT *
FROM product
WHERE product.data @> '{"availability": [ { "price": 3599} ] }';
好。很好。
但是我还需要找到价格> 1000
我尝试这个:
select *
from product
where to_tsvector(product.data #>> '{availability}') @@ to_tsquery('>1000')
但是结果为空(没有找到)。
解决方法
全文搜索是这种查询的错误工具。
在Postgres 12中,您可以使用JSON / Path表达式:
select *
from product
where data @@ '$.availability[*].price > 100';
对于较旧的Postgres版本,您需要取消嵌套该数组:
select *
from product
where exists (select *
from jsonb_array_elements(data -> 'availability') as x(item)
where (x.item ->> 'price')::int > 100);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。