假设我有一张桌子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;
这可能吗?我可以看到,如果你在同一个对象上有color
和Color
键可能会发生冲突,所以如果这不是一件事我也不会感到惊讶。
参考文献:
你应该提取对(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.
每行执行一次