MySql表与sum合并

时间:2013-05-28 15:19:30

标签: mysql merge sum

我的twp表就像这样。

+----+--------+   +----------+-------+--------+
| id | fruit  |   | fruit_id | color | amount |
+----+--------+   +----------+-------+--------+

结果:

SELECT
  fruit,amount
FROM
  table1,table2
WHERE fruit_id = id

+--------+--------+
| fruit  | amount |
+--------+--------+
| Apple  |      5 |
| Apple  |      5 |
| Cherry |      2 |
| Cherry |      2 |
+--------+--------+

但我想要这个结果:

+--------+--------+
| fruit  | amount |
+--------+--------+
| Apple  |     10 |
| Cherry |      4 |
+--------+--------+

1 个答案:

答案 0 :(得分:2)

您将使用汇总函数sum()GROUP BY来获得结果:

SELECT t1.fruit, sum(t2.amount) Total
FROM table1 t1
inner join table2
  on t2.fruit_id = t1.id
group by t1.fruit

作为旁注,您应该使用标准ANSI连接语法和INNER JOIN。