可以直接使用mysql的sum函數(shù)求和,mysql會(huì)自動(dòng)轉(zhuǎn)換為數(shù)字型進(jìn)行求和.
成都創(chuàng)新互聯(lián)公司是一家以重慶網(wǎng)站建設(shè)公司、網(wǎng)頁(yè)設(shè)計(jì)、品牌設(shè)計(jì)、軟件運(yùn)維、seo優(yōu)化排名、小程序App開(kāi)發(fā)等移動(dòng)開(kāi)發(fā)為一體互聯(lián)網(wǎng)公司。已累計(jì)為成都食品包裝袋等眾行業(yè)中小客戶提供優(yōu)質(zhì)的互聯(lián)網(wǎng)建站和軟件開(kāi)發(fā)服務(wù)。
php+mysql,
舉個(gè)例子
...........省略數(shù)據(jù)庫(kù)連接3步驟
$sql
=
"select
sum(price)
from
table";
//查詢price字段下所有值的和
$query
=
mysql_query($sql);
//執(zhí)行sql語(yǔ)句
$result
=
mysql_fetch_row($query);
//取得搜索結(jié)果中的數(shù)據(jù)(一個(gè)數(shù)組)
echo
$result[0];
//
數(shù)組中只有一條數(shù)據(jù),所以索引
就可以了
echo就是顯示啦,
希望能幫到你
SELECT SUM(分?jǐn)?shù)) FROM 表a WHERE 性別='男'
SELECT SUM(分?jǐn)?shù)) FROM 表a WHERE 性別='女'
----測(cè)試
CREATE TABLE MASK_TEST(
ID INT,
姓名 varchar(20),
性別 varchar(20),
年齡 int,
分?jǐn)?shù) int
)
INSERT INTO MASK_TEST VALUES(11,'ZHANG SAN','男',20,88)
INSERT INTO MASK_TEST VALUES(11,'LIU SHAN','女',20,83)
INSERT INTO MASK_TEST VALUES(11,'WANG SAN','男',20,87)
INSERT INTO MASK_TEST VALUES(11,'ZHANG TING','女',20,83)
INSERT INTO MASK_TEST VALUES(11,'ZHAO YAN','女',20,88)
INSERT INTO MASK_TEST VALUES(11,'ZHOU HU','男',20,78)
INSERT INTO MASK_TEST VALUES(11,'WANG QIANG','男',20,98)
INSERT INTO MASK_TEST VALUES(11,'LI QIAN','女',21,68)
SELECT SUM(分?jǐn)?shù)) FROM MASK_TEST WHERE 性別='男'
SELECT SUM(分?jǐn)?shù)) FROM MASK_TEST WHERE 性別='女'
----結(jié)果:
(1 行受影響)
(1 行受影響)
(1 行受影響)
(1 行受影響)
(1 行受影響)
(1 行受影響)
(1 行受影響)
(1 行受影響)
-----------
351
(1 行受影響)
-----------
322
(1 行受影響)
function?sumShuzi($tree,?$updateData?=?array())?{
$sum?=?0;
//?foreach($tree?as?$key?=?$item)?{??//這句話有毒
foreach($tree?as?$key?=?$item)?{
if(isset($item['children']))?{
$oldPshuzi?=?$tree[$key]['Pshuzi'];
$tree[$key]['Pshuzi']?=?sumShuzi($item['children'],?$updateData);
if($oldPshuzi?!=?$tree[$key]['Pshuzi'])?{
$updateData[$item['id']]?=?array($tree[$key]['Pshuzi'],?$tree[$key]['Pname_ch']);
}
}
$sum?+=?$tree[$key]['Pshuzi'];
}
return?$sum;
}
$tree?=?json_decode('[{"id":"1","Pid":"0","Pname_ch":"\u6e20\u9053\u90e8","Pshuzi":"1638000","children":[{"id":"4","Pid":"1","Pname_ch":"\u9500\u552e\u4e8c\u90e8","Pshuzi":"895000","children":[{"id":"13","Pid":"4","Pname_ch":"\u5468\u7ecf\u7406","Pshuzi":"28","children":[{"id":"28","Pid":"13","Pname_ch":"\u6e56\u5357","Pshuzi":"158000"},{"id":"35","Pid":"13","Pname_ch":"\u65b0\u7586","Pshuzi":"19000"}]},{"id":"40","Pid":"4","Pname_ch":"\u9648\u7ecf\u7406","Pshuzi":"5000"}]}]}]',?true);
//$tree是具有父子關(guān)系的數(shù)據(jù)樹(shù)
sumShuzi($tree,?$updateData);
foreach?($updateData?as?$id?=?$item)?{
$sql?=?"update?your_table?set?Pshuzi={$item[0]}?where?id={$id}";
mysqli_query($db,?$sql);????//$db是你的數(shù)據(jù)庫(kù)連接結(jié)果
}