如何在PostgreSQL中选择不区分大小写的JSONB密钥(9.4+)

问题描述 投票:7回答:1

Setup (PostgreSQL 9.4+)

假设我有一张桌子product

create table product
(
    attributes jsonb
);

有数据:

insert into product (attributes) 
values ('{"Color": "Red"}'), 
       ('{"color": "White"}'),
       ('{"COLOR": "Blue"}');

Question

如何在PostgreSQL 9.4+中选择所有记录的color属性?由于键的外壳不同,我无法使用此语法:

select 
    attributes->>'color' as color
from product;

我的预期输出是:

Red
White
Blue

Possible Solution

我也试过使用这种语法(工作但感觉很难):

select 
    coalesce(
        attributes->>'color', 
        attributes->>'Color', 
        attributes->>'COLOR') as color 
from product;

这可能吗?我可以看到,如果你在同一个对象上有colorColor键可能会发生冲突,所以如果这不是一件事我也不会感到惊讶。

参考文献:

json postgresql postgresql-9.4 jsonb
1个回答
10
投票

你应该提取对(key, value)使用函数lower()

select value as color
from product, jsonb_each(attributes)
where lower(key) = 'color';

或使用更详细的语法:

select value as color
from product
cross join jsonb_each(attributes)
where lower(key) = 'color';

这个cross join是一个横向连接,函数jsonb_each()product.每行执行一次

© www.soinside.com 2019 - 2024. All rights reserved.