簡體   English   中英

返回所有組合,包括空值

[英]Return all combinations including nulls

我認為這個問題非常接近我的需要,但我無法解開它來提供我需要的數據。

我有4組數據:

TableA    TableB    TableC   TableD
1         10        20       34
2         15        21
3         16
          17

我希望能夠獲得每個組合,包括空白行,所以我的結果如下所示:

TableA_id  TableB_id  TableC_id  TableD_id
1          NULL       NULL       NULL
1          10         NULL       NULL
1          10         20         NULL
1          10         20         34
1          10         21         NULL
1          10         20         34
1          15         NULL       NULL
1          15         20         NULL
1          15         20         34
1          15         21         NULL
1          15         21         34
... but then to also include ...
NULL       10         NULL       NULL
NULL       10         20         NULL
NULL       10         20         34   
NULL       10         21         NULL
NULL       10         21         34   
...
NULL       NULL       NULL       34

使用下面的CROSS JOIN可以獲得所有完整組合,但要獲得部分組合,我能看到的唯一解決方案是UNION單獨的查詢,每個查詢都讓我得到原始的所有單/雙/三值行。

SELECT TableA.id AS TableA_id, TableB.id AS TableB_id, TableC.id AS TableC_id, TableD.id AS TableD_id
FROM TableA CROSS JOIN
    TableB CROSS JOIN
    TableC CROSS JOIN
    TableD

使用UNION ALL在每個表中添加具有NULL值的行,然后CROSS JOIN所有查詢:

select *
from (select id as id_a from tablea union all select null) a 
cross join (select id as id_b from tableb union all select null) b 
cross join (select id as id_c from tablec union all select null) c
cross join (select id as id_d from tabled union all select null) d
where coalesce(a.id_a, b.id_b, c.id_c, d.id_d) is not null

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM