SQL UNION或类似提供缺少的行? (拿两个)

时间:2015-08-20 07:34:53

标签: sql ms-access-2010

鉴于两个表:

T_A

Key_A   A_1
1       A
2       B
3       C

T_B

Key_B    Key_A  B_1
10       1      X
10       2      Y
10       3      Z
20       1      D
20       2      E
30       1      L

我想生成以下输出集

T_X

Key_B   Key_A   A_1    B_1
10      1       A      X
10      2       B      Y
10      3       C      Z
20      1       A      D
20      2       B      E
20      3       C      NULL   <-- Missing row to also be returned
30      1       A      L
30      2       B      NULL   <-- MRTABR
30      3       C      NULL   <-- MRTABR

(Take 1)

中提供的以下SQL示例
select distinct T_B.Key_B, T_A.Key_A, T_A.A_1
from T_B
cross join T_A

select sq.Key_B, T_A.Key_A, T_A.A_1
from (select distinct Key_B from T_B) sq
cross join T_A

如果结果集中不需要Column T_B.B_1,两者都能很好地工作。

如何将SQL修改为现在包含T_B.B_1?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

select distinct b.Key_B, a.Key_A, a.A_1, b1.B_1
from T_A a cross join (select key_b from T_B) b
left join T_B b1 on b1.Key_B = b.Key_B and b1.Key_A = a.Key_A;

编辑:由于Access2k不支持cross join,因此可以将查询重写为:

select distinct c.Key_B, c.Key_A, c.A_1, B1.B_1 
from (
    select a.Key_A, a.A_1, b.Key_B 
    from T_A a, (select key_b from T_B) b
) c 
left join T_B b1 on B1.Key_B = c.Key_B and B1.Key_A = c.Key_A ;