我有三张桌子A,B和C.
表C
ID1 ID2
1 10
2 15
3 18
表A
ID1 Name
1 John
2 Jon
3 William
10 Willy
15 Jack
18 George
表B
ID2 Address
1 abc
2 def
3 ghi
10 jkl
15 mno
18 pqr
我需要输出,使得来自Table C
的每一行都是一个接一个地来自各自的表中的相应名称,如下所示:
预期输出
ID Name Address
1 John abc
10 Willy jkl
2 Jon def
15 Jack mno
so on...
此处ID2
是foreign key
。
我尝试了UNION
,但它首先提供了与ID1
相对应的所有记录,然后是ID2
。
答案 0 :(得分:1)
使用CTE:
;WITH CTE
AS
(
SELECT c.ID1 As Order1, 1 as Order2, a.ID1, A.Name, b.Address
FROM a
INNER JOIN b
ON a.ID1 = B.ID2
INNER JOIN c
ON c.ID1 = a.ID1
UNION ALL
SELECT c.ID1 As Order1, 2 as Order2, a.ID1, A.Name, b.Address
FROM a
INNER JOIN b
ON a.ID1 = B.ID2
INNER JOIN c
ON c.ID2 = a.ID1
)
SELECT ID1, Name, Address
FROM CTE
ORDER by order1, Order2
答案 1 :(得分:0)
尝试下面
SELECT i.id, i.NAME, i.address
FROM (SELECT 1 A,
Row_number() OVER(ORDER BY i.id1) ordr,
ID,
A.NAME,
B.address
FROM tablec i
INNER JOIN TableA A
ON i.id1 = A.id1
INNER JOIN TableB B
ON i.id1 = B.id2
UNION ALL
SELECT 2 A,
Row_number() OVER(ORDER BY i.id1) ordr,
i.id2 ID,
A.NAME,
B.address
FROM tablec i
INNER JOIN TableA A
ON i.id2 = A.id1
INNER JOIN TableB B
ON i.id2 = B.id2) i
ORDER BY i.ordr, i.a
答案 2 :(得分:0)
使用OUTER APPLY
:
SELECT
a.ID1 AS ID,
a.Name,
b.Address
FROM TableA a
INNER JOIN TableB b
ON b.ID2 = a.ID1
OUTER APPLY(
SELECT ID1, ID2
FROM TableC
WHERE
ID1 = a.ID1
OR ID2 = a.ID1
)c
ORDER BY
c.ID1, a.ID1
<强> RESULT 强>
ID Name Address ID1* ID2*
----------- ---------- ---------- ----------- -----------
1 John abc 1 10
10 Willy jkl 1 10
2 Jon def 2 15
15 Jack mno 2 15
3 William ghi 3 18
18 George pqr 3 18
ID1
和ID2
包含在结果中以供解释。
OUTER APPLY
将返回TableC
的匹配行,该行定义您的订单。您可以按c.ID1
和a.ID1
进行简单排序。