我正在连接三个表(执行完全外部连接),以便可以从所有表中检索所有记录。我面临的问题是我加入表格的顺序。
表信息
替代文字 http://img235.imageshack.us/img235/7980/tableinfoow1.png
(1) 如果我以 TABLE1、TABLE2、TABLE3 的顺序连接表,我会得到两行记录,用于团队 B 和级别 1。
SELECT DISTINCT
(CASE WHEN T0.[TEAM] IS NOT NULL THEN T0.[TEAM] WHEN T1.[TEAM] IS NOT NULL THEN T1.[TEAM] WHEN T2.[TEAM] IS NOT NULL THEN T2.[TEAM] ELSE T0.[TEAM] END) AS [TEAM],
(CASE WHEN T0.[LEVEL] IS NOT NULL THEN T0.[LEVEL] WHEN T1.[LEVEL] IS NOT NULL THEN T1.[LEVEL] WHEN T2.[LEVEL] IS NOT NULL THEN T2.[LEVEL] ELSE T0.[LEVEL] END) AS [LEVEL],
T0.[VALUE1] AS [VALUE1],
T1.[VALUE2] AS [VALUE2],
T2.[VALUE3] AS [VALUE3]
FROM TABLE1 T0
FULL JOIN TABLE2 T1 ON T0.[TEAM] = T1.[TEAM] AND T0.[LEVEL] = T1.[LEVEL]
FULL JOIN TABLE3 T2 ON T0.[TEAM] = T2.[TEAM] AND T0.[LEVEL] = T2.[LEVEL]
(2) 如果我在 TABLE2、TABLE3、TABLE1 序列中加入表,我会在输出中得到正确的行数。
SELECT DISTINCT
(CASE WHEN T0.[TEAM] IS NOT NULL THEN T0.[TEAM] WHEN T1.[TEAM] IS NOT NULL THEN T1.[TEAM] WHEN T2.[TEAM] IS NOT NULL THEN T2.[TEAM] ELSE T0.[TEAM] END) AS [TEAM],
(CASE WHEN T0.[LEVEL] IS NOT NULL THEN T0.[LEVEL] WHEN T1.[LEVEL] IS NOT NULL THEN T1.[LEVEL] WHEN T2.[LEVEL] IS NOT NULL THEN T2.[LEVEL] ELSE T0.[LEVEL] END) AS [LEVEL],
T0.[VALUE1] AS [VALUE1],
T1.[VALUE2] AS [VALUE2],
T2.[VALUE3] AS [VALUE3]
FROM TABLE2 T0
FULL JOIN TABLE3 T1 ON T0.[TEAM] = T1.[TEAM] AND T0.[LEVEL] = T1.[LEVEL]
FULL JOIN TABLE1 T2 ON T0.[TEAM] = T2.[TEAM] AND T0.[LEVEL] = T2.[LEVEL]
我面临的问题是我不知道输入表并在运行时将所有这些表作为用户的输入并执行连接。我不能一次合并两个表,因为从技术上讲,我的表一次可以合并三个以上的表(最多 9 个或 10 个)。
如何确保从所有表中获取所有记录(使用完全外连接),但不要像 #1 中那样获取两行。