我想 这个 这个问题和我需要的很接近,但是我一直无法解开它来给出我所需要的数据。
我有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
请看... 演示.