需要MySQL查询帮助

时间:2010-12-09 13:05:11

标签: mysql

我对MySQL比较陌生,而且我可能无法通过一个查询实现我想要的东西。我有以下表结构:

name | value1 | value2

我有几条记录,其中名称相同但值不同。我想做的是选择不同的名称,但应添加它们的值。这是一个例子:

john | 1 | 2
jane | 6 | 3
mark | 2 | 5
mark | 3 | 1

因此查询(如果可能)将返回

john | 1 | 2
jane | 6 | 3
mark | 5 | 6

4 个答案:

答案 0 :(得分:3)

是的,您可以使用group by

select name , sum(value1) as sum1, sum(value2) as sum2 from mytable group by name

答案 1 :(得分:2)

您使用group by with aggregate functions。

SELECT name, sum(value1) as total1,sum(value2) as total2 FROM mytable GROUP BY name

答案 2 :(得分:2)

SELECT name, sum(value1) as column1 ,sum(value2) as column2 
FROM mytable 
GROUP BY name

我建议学习一些lessons on MySQL。 作为初学者,我非常乐于助人。

答案 3 :(得分:0)

$query = "SELECT name, SUM(value1) as v1, SUM(value2) as v2 FROM table GROUP BY name";