使用一个表加入三个表

时间:2016-02-01 00:42:59

标签: mysql sql

我有一个连接其他三个表的表。

表SPP:

+------------+---------------+-------+  
| SPP_Code   |  City         | County 
+------------+---------------+-------+

表SPB:

+------------+---------------+-------+-------+  
| SPB_code   | SPP_Code      |  Name | Add1     
+------------+---------------+-------+-------+

表五:

+------------+---------------+-------+  
| vw_Code    | customer      |SPB_code|  
+------------+---------------+-------+

表数字:

+------------+---------------+-------+---------+  
| Num_Jref   | vw_Code       | period|  Amount  
+------------+---------------+-------+---------+

我需要找出SPB_code,姓名,城市,县,ADD1,2015/01年度至2015/03年度之间的总金额

到目前为止我已经完成了这项工作,但不确定如何连接其中两个查询。

查询1:

SELECT spb.SPB_code, spb.Name, spb.ADD1, SUM (num.Amount_1) AS   sum_amount_1

FROM SPB spb 
INNER JOIN VW vw
ON spb.SPB_Code = vw.SPB_Code

INNER JOIN Num nm
ON vw.Code = nm.CODE
WHERE   nm.period  >= '201501'
AND     nm.period  <= '201503'
GROUP BY spb.SPB_code, spb.Name, spb.ADD1 ;

QUERY2:

SELECT DISTINCT spb.SPB_code, spp.SPP_Code, spp.City, spp.County
from SPB spb 
JOIN  SPP spp   
ON spb.SPB_code =spp.SPP_Code

任何帮助将不胜感激。 感谢

2 个答案:

答案 0 :(得分:0)

如果您只想根据您指定的列找到总金额,则以下查询将有效,

  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <div id="chart_div"></div>
      

答案 1 :(得分:0)

你必须在其外键上加入所有相关的表格,并将你要查询的所有字段分组,希望这有助于解决你的问题。

SELECT
spb.SPB_Code, spb.Name, spp.City, spp.Country, spb.Add1
FROM
SPB spb
inner join SPP spp on spp.SPP_Code = spb.SPP_Code
inner join VW vw on vw.SPB_Code = spb.SPB_Code
inner join Num num on num.vw_Code = vw.vw_Code
WHERE
num.period >= '201501'
AND
num.period <= '201503'
GROUP BY 
spb.SPB_Code, spb.Name, spp.City, spp.Country, spb.Add1