Mar*_*cke 8 postgresql json jsonb postgresql-9.4
假设我有一张桌子product:
create table product
(
attributes jsonb
);
Run Code Online (Sandbox Code Playgroud)
有数据:
insert into product (attributes)
values ('{"Color": "Red"}'),
('{"color": "White"}'),
('{"COLOR": "Blue"}');
Run Code Online (Sandbox Code Playgroud)
如何color在PostgreSQL 9.4+中选择所有记录的属性?由于键的外壳不同,我无法使用此语法:
select
attributes->>'color' as color
from product;
Run Code Online (Sandbox Code Playgroud)
我的预期输出是:
Red
White
Blue
Run Code Online (Sandbox Code Playgroud)
我也试过使用这种语法(工作但感觉很难):
select
coalesce(
attributes->>'color',
attributes->>'Color',
attributes->>'COLOR') as color
from product;
Run Code Online (Sandbox Code Playgroud)
这可能吗?我可以看到,如果你拥有color并Color锁定同一个对象可能会发生冲突,所以如果这不是一件事我也不会感到惊讶.
参考文献:
kli*_*lin 11
您应该提取对(key, value)以使用该功能lower()
select value as color
from product, jsonb_each(attributes)
where lower(key) = 'color';
Run Code Online (Sandbox Code Playgroud)
或使用更详细的语法:
select value as color
from product
cross join jsonb_each(attributes)
where lower(key) = 'color';
Run Code Online (Sandbox Code Playgroud)
这cross join是一个横向连接,该函数jsonb_each()每行执行一次product.
| 归档时间: |
|
| 查看次数: |
1643 次 |
| 最近记录: |