我有一个使用This Link编写的查询。
SQL Fiddle,以防上述链接过期。
示例代码:
;WITH MentorTable (CommonId, MentorId, MentorName) AS
(
SELECT ROW_NUMBER() OVER(ORDER BY MentorId) AS CommonId,MentorId, MentorName
FROM Mentor
)
,MenteeTable (CommonId, MenteeId, MenteeName) AS
(
SELECT ROW_NUMBER() OVER(ORDER BY MenteeId) AS CommonId,MenteeId, MenteeName
FROM Mentee
)
SELECT MR.MentorId,MR.MentorName,ME.MenteeId,ME.MenteeName
FROM MentorTable MR
LEFT OUTER JOIN MenteeTable ME ON MR.CommonId = ME.CommonId
我想从五个表中获取数据并加入它们,而它们之间没有任何公共列。以上查询帮助我实现了这一目标。但是,在上面的查询中,Mentortable(来自表)将始终具有比其他表更多的记录,因此其他表的所有记录将在剩余行上显示为null。
然而,在我的五个表中,我不知道哪个表会有更多的记录。我希望我的查询从该表中进行选择,以便其余表中的任何行都不会错过。此外,我必须相应地更改我的连接表,以便所有其余的表除了" from table"加入了。任何帮助将不胜感激。
答案 0 :(得分:1)
一种方法是full outer join
。在您的情况下,这看起来像:
WITH MentorTable (CommonId, MentorId, MentorName) AS
(
SELECT ROW_NUMBER() OVER(ORDER BY MentorId) AS CommonId,MentorId, MentorName
FROM Mentor
)
, MenteeTable (CommonId, MenteeId, MenteeName) AS
(
SELECT ROW_NUMBER() OVER(ORDER BY MenteeId) AS CommonId,MenteeId, MenteeName
FROM Mentee
)
SELECT COALESCE(MR.MentorId, ME.MentorId) as MentorId, MR.MentorName, ME.MenteeId, ME.MenteeName
FROM MentorTable MR FULL OUTER JOIN
MenteeTable ME
ON MR.CommonId = ME.CommonId;
然而,当您添加更多条件时,这会变得很麻烦。 on
子句最终看起来像:
ON M5.CommonId = coalesce(M1.CommonId, M2.CommonId, M3.CommonId, M4.CommonId)
因此,您通常可以使用union all
和group by
处理此问题:
select CommonId, MAX(MentorName) as MentorName, MAX(MenteeName) as MenteeName
from ((select MR.CommonId, MR.MentorName, NULL as MenteeName from MentorTable MR) union all
(select ME.CommonId, NULL, ME.MenteeName from MentorTable ME)
) t
group by CommonId;