如何结合3个表和组相同的id量?

时间:2017-06-27 18:43:29

标签: sql

如何解决3个表和组相同的id?

   t1
----------
Id   a
1   100
1   600
2   800

  t2
----------
Id    b
1    600
2    700
3    400


  t3
----------
Id    c
2    400
3    800
4    100 

我想要这样的结果:

Id     a        b      c 
------------------------------
 1    700      600   
 2    800      700    400      
 3             400    800
 4                    100

相同的ID组

3 个答案:

答案 0 :(得分:0)

在你应该得到的几个表中你有id的事实,例如:使用union,你需要加入的所有id

  select t.id, t1.a, t2.b, t3.c
  from ( 
       select id 
       from t1
       union
       select id
       from t2 
       union 
       select id 
       from t3 ) AS t 
    left join t1 on t.id = t1.id
    left join t2 on t.Id = t2.Id
    left join t3 on t.Id = t3.Id

如果你需要总和a,b,c

   select t.id, sum(t1.a), sum(t2.b), sum(t3.c)
      from ( 
           select id 
           from t1
           union
           select id
           from t2 
           union 
           select id 
           from t3 ) AS t 
        left join t1 on t.id = t1.id
        left join t2 on t.Id = t2.Id
        left join t3 on t.Id = t3.Id
    group by t.id

答案 1 :(得分:0)

要确保获取所有可能的值,请使用完全外部联接。虽然这在mySQL中不起作用。如果是这种情况,请查看此answer

select coalesce(t1.id,t2.id,t3.id) as id, sum(t1.a) as a, sum(t2.b) as b,sum(t3.c) as c
from t1
outer join t2
   on t1.id = t2.id
outer join t3
   on t1.id = t3.id
      or t2.id = t3.id
group by id

答案 2 :(得分:0)

可能会误解你,但看起来你只需加入表而不是对它们进行联盟操作。下面的语句只返回所有三个表至少有一个具有相同id的记录的记录。

SQL将是:

SELECT TBL1.ID,
   TBL1.A,
   TBL2.B,
   TBL3.C
FROM A TBL1 (NOLOCK)
INNER JOIN B TBL2 (NOLOCK) ON TBL1.ID = TBL2.ID
INNER JOIN C TBL3 (NOLOCK) ON TBL1.ID = TBL3.ID

两个问题: 1.您使用哪个SQL引擎? 2.你需要返回一个表没有id的值吗?