[英]SQL UNION or similar to supply missing absent rows? (Take two)
Given the two tables: 给定两个表:
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
I want to produce the following output set 我想产生以下输出集
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
The following SQL samples supplied in (Take 1) (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
Both worked very well if Column T_B.B_1 was not required in the result set. 如果结果集中不需要列T_B.B_1,则两者都可以很好地工作。
How do I modify the SQL to now include T_B.B_1? 如何修改SQL,使其现在包含T_B.B_1?
You can do it like this: 您可以这样做:
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;
edit: since Access2k doesn't supprt cross join
the query can be rewritten as: 编辑:由于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 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.