Postgres 中的递归 JSON 连接

Recursice JSONB join in Postgres

我正在尝试扩展现有系统以允许基于 JSONB 中的值的自引用“外键”关系。我举个例子加深理解

|  ID  |            DATA                                        |
|---------------------------------------------------------------|
|  1   |{building_id: 1, building_name: 'Office 1'}             |
|---------------------------------------------------------------|
|  2   |{building_id: 2, building_name: 'Office 2'}             |
|---------------------------------------------------------------|
|  3   |{building_id: 1, full_name: 'John Doe', calary: 3000}   |
|---------------------------------------------------------------|
|  4   |{building_id: 1, full_name: 'Alex Smit', calary: 2000}  |
|---------------------------------------------------------------|
|  5   |{building_id: 1, full_name: 'Anna Birkin', calary: 2500}|

我尝试使用 jsonb_array_elements_text,但我需要像这样将新数据合并到单个 JSON 字段中

|  ID  |            DATA                                                                     |
|--------------------------------------------------------------------------------------------|
|  1   |{building_id: 1, building_name: 'Office 1', full_name: 'John Doe', calary: 3000}     |
|--------------------------------------------------------------------------------------------|
|  2   |{building_id: 1, building_name: 'Office 1', full_name: 'Alex Smit', calary: 2000}    |
|--------------------------------------------------------------------------------------------|
|  3   |{building_id: 2, building_name: 'Office 2', , full_name: 'Anna Birkin', calary: 2500}|

我想知道这是否可能

假设 Anna Birkin 在 building_id 2 中,并且这些不同的对象类型足够一致,可以通过键的存在来确定类型,请尝试这样的事情:

select b.data || p.data as result
  from really_bad_idea b
       join really_bad_idea p on p.data->'building_id' = b.data->'building_id'
 where b.data ? 'building_name'
   and p.data ? 'full_name';

db<>fiddle here