将多个表连接到一个Id下

时间:2012-05-11 12:08:05

标签: sql sql-server database tsql join

我有十几个表格,格式如下:

表1

[idA] [numA]
 NULL   8
 1      10
 2      15
 3      16

表2

[idB] [numB]
 2      14
 3      30
 4      32

表3

[idC] [numC]
 NULL   56
 1      24
 4      37
 5      36

...

现在,我不确定如何制定T-Sql查询以产生以下结果:

[id] [numA] [numB] [numC] ...
NULL  8      0      56
1     10     0      24
2     15     14     0
3     16     30     0
4     0      32     37
5     0      0      36

有关于如何解决这个问题的建议吗?

3 个答案:

答案 0 :(得分:2)

我提供了一个完整外连接的解决方案,因为这似乎是一种自然的方法:

SELECT coalesce(a.id, b.id, c.id, . . .) as id,
       a.NumA, b.NumB, c.NumC, . . .
FROM TableA a full outer join
     TableB b
     on a.id = b.id full outer join
     TableC c
     on coalesce(a.id, b.id) = c.id

但是,需要仔细编写查询,以保持合并。这种方法的一个优点是它应该在查询的id列上使用索引。

答案 1 :(得分:1)

请试试这个

select id, max(numa),max(numb),max(numc) from
(
select id,numa,0 as numb,0 as numc from tb1
union all
select id,0 as numa,numb as numb,0 as numc from tb2
union all
select id,0 as numa,0 as numb,numc as numc from tb3
)X
group by id
order by id

由于 Rajath

答案 2 :(得分:0)

SELECT Maintable.id, 
       Table1.numA, 
       Table2.numB, 
       Table3.numC 
FROM   (SELECT ida AS id 
        FROM   Table1 
        UNION 
        SELECT idb AS id 
        FROM   Table2 
        UNION 
        SELECT idc AS id 
        FROM   Table3) MainTable 
       LEFT JOIN Table1 
         ON Maintable.id = Table1.Ida 
       LEFT JOIN Table2 
         ON Maintable.id = Table2.idB 
       LEFT JOIN Table3 
         ON Maintable.id = Table3.idC