sql - json字段上的PosgtreSQL连接表
问题描述
假设我们有 2 张桌子-
员工:
id integer
(PK)name char
code char
状态:
id integer
(PK)key char
data jsnob
现在这里是上表的示例数据:
员工
+----+--------+------+
| id | name | code |
+----+--------+------+
| 1 | Brian | BR1 |
| 2 | Andrew | AN1 |
| 3 | Anil | AN2 |
| 4 | Kethi | KE1 |
| 5 | Smith | SM1 |
+----+--------+------+
地位
+----+---------+---------------------------------------+
| id | key | data |
+----+---------+---------------------------------------+
| 1 | Admin | {'BR1':true, 'AN1':true,'KE1':false} |
| 2 | Staff | {'SM1':true, 'AN2':true,'KE1':false} |
| 3 | Member | {'AN2':false, 'AN1':true,'KE1':false} |
| 4 | Parking | {'BR1':true, 'AN1':true,'KE1':false, |
| | | 'AN2':true,'SM1':true} |
| 5 | System | {'AN2':false, 'AN1':true,'KE1':true} |
| 6 | Ticket | {'AN2':false, 'AN1':true,'KE1':false} |
+----+---------+---------------------------------------+
现在我的目标是获取故障键的状态和名称,员工代码明智。例如:-
我不是 sql 复杂查询方面的专家,因此非常感谢任何帮助。
注意:以上只是示例表(名称和数据已更改),但设计与原始表相似。
解决方案
在这些表之间使用左连接查询,并为类型列应用jsonb_each_text()
函数。jsonb
诀窍是对case when (js).value = 'false' then .. else .. end
聚合列使用条件:
select e.id, e.code,
min(case when (js).value = 'false' then 'FALSE' else 'TRUE' end ) as status,
count(case when (js).value = 'false' then 1 end) as failures,
coalesce(
string_agg(case when (js).value = 'false' then s.key end, ',' ORDER BY s.id),'NA'
) as key
from Employee e
left join
(
select *, jsonb_each_text(data) as js
from Status
) s on e.code = (js).key
group by e.id, e.code
order by e.id;
从类型列中(js).value
提取的位置jsonb
Status.data
推荐阅读
- php - 验证功能在wordpress中不起作用
- hyperledger-fabric - 创建频道时出错,但此政策需要满足 1 个“作家”子政策:权限被拒绝
- spring-boot - 如何修复原因:tomcat 部署 8.5.27 上的“java.lang.NoClassDefFoundError: javax/management/MBeanServerNotification”
- python - 如何在 VSC 中使用“打开”命令?
- r - 在 R 中使用 osmplotr 和 OpenStreetmap 绘制海域
- php - 如何在php中的foreach循环后重置对象指针?
- c# - 选中的组合框文本有问题
- c - 如何在c中使用libav
- r - 如何计算组的倍数变化?
- bash - 使用 gsed 将重音单词大写