我有一个 mysql 表,其中包含一个名为“id”、“name”和“number”的字段。
每行的“数字”字段都有一个数字。
id name number
1 test 30
2 test2 40
3 lala 23
total = 93
如何计算(加)所有行数?
$row['number']+$row['number']+$row['number'] = .. an other number.
SELECT name, SUM(number) FROM table GROUP BY name
我假设您想按名称进行总和。
SELECT SUM(number) FROM table
不分组。
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum了解更多信息
尝试这样做
select number ,sum(number) as total from table;
然后做
$row['total'] // and it gives u the total sum
在 PHP 级别:
$cnt = 0;
while($row = mysql_fetch_assoc($result)) {
$cnt += $row['yourfield'];
}
在 MySQL 级别:
SELECT SUM(yourfield)
FROM yourtable
GROUP BY yourfield
您可以像这样查询表:
select sum(number) from table;
并让mysql为你计算。
尝试这个
SELECT SUM(number) AS total FROM table;