sql - Postgresql - 从 [] 值中提取 json 值
问题描述
在 postgresql 中,我试图查询一个视图,其中一个名为codeids
jsonb 的列的类型看起来像这样 - ["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"]
。我想查询这一列,结果每行返回一个值。在上面的示例中,查询应该返回 3 行。
我已经使用json_array_elements
和jsonb_array_length
提取部分 json 结构对完全形成的 json blob 运行查询。但是有人这个更简单的 json 结构让我感到困惑,因为我无法找出 postgresql 语句提取这三个值的正确格式。提前致谢。
SELECT
role -> 'title' AS team_role,
jsonb_array_length(role -> 'names') AS member_count
FROM jsonb_array_elements(value -> 'team') AS team(role)
解决方案
你快到了......但你需要在查询中带来实际的表(或视图)。我发现LATERAL JOIN
语法在这里更明显:
SELECT
t.role -> 'title' AS team_role,
jsonb_array_length(t.role -> 'names') AS member_count
FROM myview v
CROSS JOIN LATERAL jsonb_array_elements(v.codeids -> 'team') AS t(role)
编辑:如果您将 jsonb 数组存储在表列中,那就更简单了:
create table test_table (codeids jsonb);
insert into test_table(codeids) values ('["Code-oyg0vYNpL", "Code-m9db_s", "Code89nb"]');
select x.role
from test_table t
cross join lateral jsonb_array_elements(t.codeids) x(role);
| role |
| -------------- |
| Code-oyg0vYNpL |
| Code-m9db_s |
| Code89nb |
推荐阅读
- html - 在没有任何唯一标识符的硒中定位元素
- python - 通过命令行修复python安装
- twitter-bootstrap - 引导断点如何区分具有相同分辨率的移动设备和全尺寸显示器?
- arrays - 试图弄清楚为什么我的 C 程序只抓取我重复的数字之一
- python - Discord bot:如何检查网址是否有效?
- r - 如何在R中将字符列转换为日期时间
- powershell - 用于关闭 VM 并分离 ISO 的 vSphere 脚本
- node.js - 在 nginx 不工作的情况下为节点代理启用 hsts
- php - php 代码有效,但警告:未定义的数组键 php
- node.js - 如何解决 sequelize.import 不是函数?