Modify/flatten 来自 sql 具有多个连接的一对多查询的结果

Modify/flatten result from sql one to many query with multiple joins

考虑以下简化模式示例 -

sys_systems

id   name
---------------------
1    Inventory


sys_shadow_data

id   primary_key_value   sys_schema_id   field_value
---------------------------------------------------------
1    1                   143             Awaiting audit
2    1                   144             90


sys_schemas

id      field_name
-------------------
143     notes
144     status

以下查询-

select sys_systems.*, 
(select sys_shadow_data.field_value where sys_schemas.field_name = 'status') as status, 
(select sys_shadow_data.field_value where sys_schemas.field_name = 'notes') as notes 
from sys_systems
    left join sys_shadow_data
        on sys_systems.id = sys_shadow_data.primary_key_value
            left join sys_schemas
                on sys_schemas.id = sys_shadow_data.sys_schema_id

产量 -

id   name       status    notes
-----------------------------------------
1    Inventory  90        null
1    Inventory  null      Awaiting audit

我想得到的结果是-

id   name       status    notes
-----------------------------------------
1    Inventory  90        Awaiting audit

我是否可以对 sql 查询进行更改以实现此目的,或者在这种情况下我需要在应用程序代码中处理结果?

您的查询相当于从 sys_schemas table 中旋转 field_name 列上的联接 table,以便为该列中的每个值生成新列。您可以 GROUP BY 库存 ID 和名称,然后使用 MAX 将两条记录合二为一:

SELECT sys_systems.id,
       sys_systems.name,
       MAX(CASE WHEN sys_schemas.field_name = 'status'
                THEN sys_shadow_data.field_value ELSE NULL END) AS status, 
       MAX(CASE WHEN sys_schemas.field_name = 'notes'
                THEN sys_shadow_data.field_value ELSE NULL END) AS notes 
FROM sys_systems
LEFT JOIN sys_shadow_data
    ON sys_systems.id = sys_shadow_data.primary_key_value
LEFT JOIN sys_schemas
    ON sys_schemas.id = sys_shadow_data.sys_schema_id
GROUP BY sys_systems.id,
         sys_systems.name