三个表的简单查询,烦请大家给指点一下
三个表的简单查询
A表
A1
A2
A3
B表
B1
B2
B3
B4
C表
A1 B1 C1
A1 B3 C2
......
要求得到一个总表:
A1 B1 C1
A1 B2 NULL
A1 B3 C1
A1 B4 NULL
A2 B1 NULL
A2 B2 NULL
A2 B3 NULL
A2 B4 NULL
A3 B1 NULL
A3 B2 NULL
A3 B3 NULL
A3 B4 NULL
这样的SQL怎么去写?烦请大家给指点一下,谢谢
------解决方案--------------------Create Table A
(a Varchar(10),
b Varchar(10),
c Varchar(10))
Create Table B
(b Varchar(10),
d Varchar(10),
e Varchar(10))
Create Table C
(a Varchar(10),
d Varchar(10),
f Varchar(10))
Insert A Select 'a1 ', 'b1 ', 'c1 '
Union All Select 'a2 ', 'b2 ', 'c2 '
Union All Select 'a3 ', 'b1 ', 'c3 '
Insert B Select 'b1 ', 'd1 ', 'e1 '
Union All Select 'b1 ', 'd2 ', 'e2 '
Union All Select 'b1 ', 'd3 ', 'e3 '
Union All Select 'b2 ', 'd2 ', 'e4 '
Insert C Select 'a1 ', 'd1 ', 'f1 '
GO
Create View V_TEST
As
Select
TOP 100 Percent
A.a,
A.b,
A.c,
B.d,
B.e,
C.f
From
A
Inner Join
B
On A.b = B.b
Left Join
C
On A.a = C.a And B.d = C.d
Order By A.a, A.b, A.c
GO
Select * From V_TEST O
GO
Drop Table A, B, C
Drop View V_TEST
--Result
/*
a b c d e f
a1 b1 c1 d1 e1 f1
a1 b1 c1 d2 e2 NULL
a1 b1 c1 d3 e3 NULL
a2 b2 c2 d2 e4 NULL
a3 b1 c3 d1 e1 NULL
a3 b1 c3 d2 e2 NULL
a3 b1 c3 d3 e3 NULL
*/