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

13

设置(PostgreSQL 9.4+)

假设我有一个表product

create table product
(
    attributes jsonb
);

使用数据:

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

问题

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

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

我的期望输出为:

Red
White
Blue

可能的解决方案

我也尝试使用这个语法(虽然能用但感觉有点取巧):

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

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

参考资料:


3
完美措辞的问题,应该作为一个示范。 - klin
1个回答

14

你应该提取键值对(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 是一个 lateral join,函数 jsonb_each() 对于每一行来自 product. 的数据都会被执行一次。


1
jsonb_each()是我一直在寻找但却不知道存在的东西,非常感谢!还有json_each(),分别返回value作为jsonbjson;而jsonb_each_text()json_each_text()则以text形式返回value(意料之中)。key始终为text。所有内容来自Postgres文档 - dwanderson
这简直救了我,否则我会在墙上撞几个小时!而且它使用起来非常容易!非常感谢你!! - randallreedjr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接