在 postgresql 查询中将变量放入 json_extract_path_text

Put variable inside json_extract_path_text in postgresql query

我关注select:

select json_extract_path_text(rules, 'amount', '5', 'percentage')
from promotion_rules

来自 JSON 的样本如下所示:

{
    "amount": {

        "1": {
            "percentage": 1
        },
        "2": {
            "percentage": 3
        },
        "3": {
            "percentage_below_eq": 5,
            "percentage_above": 10,
            "price": 20
        },
        "4": {
            "percentage_below_eq": 10,
            "percentage_above": 15,
            "price": 20
        }
    }
}

我想在上面的 json_extract 函数中使用其他 queries/tables/cte 的值而不是“5”(或达到准确的效果),如何实现?

这是代码的一部分,fiddle 有完整的数据,我不能把它全部放在这里因为堆栈告诉我我的 post 我主要是代码。

with percentages as (select pr.*, json_object_keys(rules->'amount')::INT as amount
from
promotion_rules pr
where id = 1
)
select
o.id as order_id,
json_extract_path_text(rules, 'amount', o.products_no, 'percentage') as percentage --it doesn't work this way, either with brackets
from orders o
join percentages p on p.amount = o.products_no

https://www.db-fiddle.com/f/oSQ3eW2G3kHgr3xvpHLw9Q/0

json_extract_path 需要一个 text 参数列表。

如果您想使用不是文本的列,则需要对其进行转换:

json_extract_path_text(rules, 'amount', o.products_no::text, 'percentage')