2013-05-28 74 views
0

我這樣的twp表。與總和合並的MySql表

+----+--------+ +----------+-------+--------+ 
| 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 | 
+--------+--------+ 

我該怎麼辦,懇求幫助我..
Thenks ...

回答

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。

+0

+1擊敗了我。 – Kermit

+0

This OK「SELECT fruit,sum(amount)Total FROM table1 inner join table2 on fruit_id = id group by fruit」Thenks ... –

+0

@MahmutEsinti是的,這是正確的,應該返回結果。 – Taryn