我的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 |
+--------+--------+
答案 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。