多表连接查询的最佳实践

时间:2012-06-11 10:41:30

标签: sql sql-server sql-server-2008 sql-server-2008-r2

表结构如下:

Table1 (ID int, value1 int,...)

ID       Value1
----    --------
1        10
2        20
5        12


Table2 (ID int, value2 int,...)

ID       Value2
----    --------
1        13
3        24
4        11


Table3 (ID int, value3 int,...)
ID       Value3
----    --------
4        150
5        100

我的预期产量低于。

ID       Value1        Value2        Value3
----    --------      --------      --------
1         10            13             NULL
2         20            NULL           NULL
3         NULL          24             NULL
4         NULL          11             150
5         12            NULL           100

应该注意的是,上面的表格很大,我想要有最好的表现。

我的查询建议如下:

Select ID, 
       SUM(Value1) AS Value1, 
       SUM(Value2) AS Value2,
       SUM(Value3) AS Value3 
From (
    Select ID, Value1 , NULL as value2, NULL as value 3
    From Table1

    Union ALL

    Select ID, NULL , value2, NULL
    From Table2

    Union ALL

    Select ID, NULL, NULL, value 3
    From Table3
    )Z
Group By Z.ID

2 个答案:

答案 0 :(得分:3)

假设每个id只有一个值,这应该可以解决问题:

SELECT aux.ID, t1.Value1, t2.Value2, t3.Value3
FROM 
(SELECT ID FROM Table1
 UNION
 select ID FROM Table2
 UNION
 SELECT ID FROM Table3) aux
LEFT OUTER JOIN Table1 t1 ON aux.ID = t1.ID
LEFT OUTER JOIN Table2 t2 ON aux.ID = t2.ID
LEFT OUTER JOIN Table3 t3 ON aux.ID = t3.ID

如果您有多个值:

SELECT aux.ID, SUM(t1.Value1) as 'Value1', SUM(t2.Value2) as 'Value2', SUM(t3.Value3) as 'Value3'
FROM 
(SELECT ID FROM Table1
 UNION
 select ID FROM Table2
 UNION
 SELECT ID FROM Table3) aux
LEFT OUTER JOIN Table1 t1 ON aux.ID = t1.ID
LEFT OUTER JOIN Table2 t2 ON aux.ID = t2.ID
LEFT OUTER JOIN Table3 t3 ON aux.ID = t3.ID
GROUP BY aux.ID

答案 1 :(得分:0)

我最初写了与aF相同的答案。在上面做了。所以,删除它,并使用不同的方法。

下面,

  
      
  • 第一个查询从table1获取所有内容
  •   
  • 第二个查询从table2跳过
  • 获取所有内容   
  • 那些已经存在于table1中的第三个查询将使所有剩余的内容跳过上述两个查询。
  •   
  SELECT T1.ID, T1.VALUE1, T2.VALUE2, T3.VALUE3 --all T1
  FROM TABLE1 T1
      LEFT JOIN TABLE2 ON T1.ID=T2.ID
      LEFT JOIN TABLE3 ON T1.ID=T3.ID
UNION
  SELECT T2.ID, T1.VALUE1, T2.VALUE2, T3.VALUE3 --all T2 where T1 is NULL
  FROM TABLE1 T2
      LEFT JOIN TABLE1 ON T2.ID=T1.ID
      LEFT JOIN TABLE3 ON T2.ID=T3.ID
  WHERE T1.ID IS NULL
UNION
  SELECT T3.ID, T1.VALUE1, T2.VALUE2, T3.VALUE3 --all T3 where T1 is NULL AND T2 IS NUL
  FROM TABLE1 T3
      LEFT JOIN TABLE1 ON T3.ID=T1.ID
      LEFT JOIN TABLE2 ON T3.ID=T2.ID
  WHERE T1.ID IS NULL
        AND T2.ID IS NULL