左连接多个表 [英] left join in multiple tables

查看:109
本文介绍了左连接多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表1:

 id amount 
1 100
2 200
3 300
4 400





表2:

 id amount 
1 100
1 100
2 200
3 300
4 null





表3:

 id amount 
1 null
2 200
2 200
3 300
< span class =code-digit> 3 200
4 null





id对于每个表都是常见的,我怎样才能获得这样的输出:

 id t1 t2 t3 
1 100 200 null
2 200 200 400
3 300 300 500
4 400 null null





i我坚持这个。

解决方案

  SELECT  
TBL1.AMOUNT T1,
TBL2.AMOUNT T2,
TBL3.AMOUNT T3
FROM TBL1
LEFT JOIN TBL2 ON TBL2.ID = TBL1.ID
LEFT JOIN TBL3 ON TBL3.ID = TBL1.ID



现在在通过OP改进问题之后,这个解决方案当然不是解决方案。


这会给你你想要的。但是我认为table1有所有的ID。



 选择 id ,(选择 sum(金额)来自 table1 st1 其中 st1.id = tbl1.id)来自 span> table2 st2 其中 st2.id = tbl1.id)t2,
select sum (金额)来自 table3 st3 其中 st3.id = tbl1.id)t3
来自 table1 tbl1







祝你好运


Table 1:

id amount
1   100
2   200
3   300
4   400



Table 2:

id   amount
1    100
1    100
2    200
3    300
4    null



Table 3:

id amount
1   null
2   200
2   200
3   300
3   200
4   null



id is common for each tables , how can i get output like this:

id  t1   t2   t3
1  100  200  null
2  200  200   400
3  300  300   500
4  400  null null



i am stuck with this .

解决方案

SELECT 
  TBL1.AMOUNT T1,  
  TBL2.AMOUNT T2,  
  TBL3.AMOUNT T3
FROM TBL1
LEFT JOIN TBL2 ON TBL2.ID = TBL1.ID
LEFT JOIN TBL3 ON TBL3.ID = TBL1.ID


Now after improving the question by OP, this solution is of course not the solution.


This will give you what you want. But I supposed that table1 has all the Ids.

select id,  (select sum(amount) from table1 st1 where st1.id=tbl1.id) t1,
            (select sum(amount) from table2 st2 where st2.id=tbl1.id) t2,
            (select sum(amount) from table3 st3 where st3.id=tbl1.id) t3
from table1 tbl1




Good Luck


这篇关于左连接多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆