在mysql中连接2个表,其中一个表有更多行并将其加总

时间:2016-03-18 09:47:07

标签: mysql

我有3张桌子

TAble A:

mydate      myid  amount
========================
2016-03-14     5    100   

表B:

mydate      myid  amount
========================
2016-03-14     5    90   
2016-03-15     2     50
2016-03-16     1     80

我想将表A和表B连接到一个新的显示结果,如下所示:

mydate      myid  amount
========================
2016-03-14     5    190   
2016-03-15     2     50
2016-03-16     1     80

请帮助

1 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL“合并”两个表,然后汇总:

SELECT mydate, myid, SUM(amount) AS amount
FROM (SELECT mydate, myid, amount
      FROM table_A
      UNION ALL
      SELECT mydate, myid, amount
      FROM table_B) AS sub
GROUP BY mydate, myid
ORDER BY mydate;