sql从两个表连接数据

时间:2015-08-02 17:54:24

标签: mysql

我想知道是否有人帮我加入两张桌子的数据......整天都没有管理......

代码1选择: 年|营业额1 |数量1 | EurPerOrder1

SELECT Year(table1.ContractDate) AS Year,
  Sum(table1.TPrice) AS Turnover1,
  Count(table1.id) AS Quantity1,
  ROUND(Sum(table1.TPrice) / Count(table1.id), 0) AS EurPerOrder1
FROM table1
GROUP BY Year(table1.ContractDate) * 100
ORDER BY table1.ContractDate DESC         

Code2选择: 年|营业额2 | Quantiry2 | EurPerOrder2

SELECT Year(table2.date) AS Year,
  Sum(table2.price) AS Turnover2,
  Count(table2.rid) AS Quantiry2,
  ROUND(Sum(table2.price) / Count(table2.rid), 0) AS EurPerOrder2
FROM table2
GROUP BY Year(table2.date) * 100
ORDER BY table2.date DESC

我需要加入以下数据:

年|营业额1 |数量1 | EurPerOrder1 |营业额2 | Quantiry2 | EurPerOrder2

我需要将两个表中的所有数据按年分组。即使table2也没有2013年,无论如何我希望它显示0或空... 我尝试了不同的方式使用示例,但没有任何工作,所以我认为问题可能发生,因为第二个表没有在table1上的所有年份......

1 个答案:

答案 0 :(得分:0)

首先:您可以阅读有关JOINS here

的非常好的解释

好的,根据你需要的问题LEFT JOIN。这意味着来自table1的所有数据和仅来自table2的匹配数据。

SELECT必须如下:

SELECT Year(table1.ContractDate) AS Year,
  Sum(table1.TPrice) AS Turnover1,
  Count(table1.id) AS Quantiry1,
  ROUND(Sum(table1.TPrice) / Count(table1.id), 0) AS EurPerOrder1, 
    Sum(table2.price) AS Turnover2,
    Count(table2.rid) AS Quantiry2, 
  ROUND(Sum(table2.price) / Count(table2.rid), 0) AS EurPerOrder2 
FROM 
    table1 t1
    LEFT JOIN table2 t2 ON Year(table1.ContractDate) = Year(table2.date)
GROUP BY 
    Year(table1.ContractDate) * 100, Year(table2.date) * 100
ORDER BY 
    table1.ContractDate DESC, table2.date DESC

当然,您需要处理NULL个值。见link

如果有错误,请检查SQL并更正它。我没有要检查的实时数据(通过运行它)。