0

My twp tables like this.

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

Result for:

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

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

But I want this result:

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

1 回答 1

2

您将使用聚合函数sum()和 aGROUP 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。

于 2013-05-28T15:20:42.003 回答