Header 和多个明细表查询问题

Header and multiple detail tables Query issue

我有 1 header table (header) 和多个细节 tables ( detail_aadetail_ab等)。

create table header (header_id int primary key, header_name varchar(100));
create table detail_aa (detail_aa_id int primary key, detail_aa_name varchar(100), header_id int foreign key references header(header_id));
create table detail_ab (detail_ab_id int primary key, detail_ab_name varchar(100), header_id int foreign key references header(header_id));

注:1具体header_id只能进去1个细节table.

例如,如果我们在 header table 中有一行 header_id = 1,那么

不可能 detail_aadetail_ab 都有包含 header_id 的行= 1.

示例:

Table: header

header_id header_name
--------- -----------
1         Master_1
2         Master_2
3         Master_3

Table: detail_aa

detail_aa_id detail_aa_name header_id
------------ -------------- ---------
101          Detail_aa_101  1

Table: detail_ab

detail_ab_id detail_ab_name header_id
------------ -------------- ---------
45           Detail_ab_45   2

我想编写一个查询,显示 header table 中的所有 header_id、header_name 以及详细信息 table 中的相应数据或 null如果没有链接:

header_id header_name detail_table_name detail_id detail_name
--------- ----------- ----------------- --------- -------------
1         Master_1    detail_aa         101       Detail_aa_101
2         Master_2    detail_ab         45        Detail_ab_45
3         Master_3    null              null      null

我该怎么做?

使用left join:

select h.*,
       (case when da.header_id is not null
             then 'detail_aa'
             else 'detail_bb'
        end),
       coalesce(da.detail_id, db.detail_id) as detail_id
       coalesce(da.detail_name, db.detail_name) as detail_name
from header h left join
     detail_aa da
     on h.header_id = da.header_id left join
     detail_bb db
     on h.header_id = db.header_id;
 

我会先合并两个明细表,然后使用左联接获取所有表头,然后详细信息(如果存在)。

With Detail as (
SELECT 'detail_aa' as detail_table_name, detail_aa_name as detail_name, Detail_aa_id as Detail_ID
UNION 
SELECT 'detail_bb' as detail_table_name, detail_bb_name as detail_name, Detail_bb_id as Detail_ID)

SELECT H.Header_Id, H.Header_Name, D.*
FROM Header H
LEFT JOIN Detail D
on H.Header_ID = D.Header_ID