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

How to select case-insensitive JSONB keys in PostgreSQL (9.4+)

设置(PostgreSQL 9.4+)

假设我有一个 table product:

create table product
(
    attributes jsonb
);

有数据:

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

问题

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

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

我的预期输出是:

Red
White
Blue

可能的解决方案

我也尝试过使用这种语法(有效但感觉很糟糕):

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

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

参考文献:

您应该提取对 (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.

的每一行执行一次