![](/img/trans.png)
[英]How to sum different columns from one table and get the sum result in another table using PHP or MySQL?
[英]MySQL Calculate sum of integer values from one column and store the result in another table
我首先要說我是mysql的新手,在這里我沒有找到關於我的問題的任何答案,也無法自己重新制作其他示例。
我有一個名為“個人資料”的表,用於存儲用戶,其中一列是存儲整數的“點”。
我有第二個表“ pointsCounter”,其中只有一列“ pointsTotal”(也是整數),該列僅存儲來自站點上每個用戶的點。
我想總結“配置文件”中的每個用戶“點”,並將結果存儲在表“ pointsCounter”中的“ pointsTotal”中。 我正在使用php進行查詢,然后將結果回顯到使用ajax請求數據的文件中。
例:
profiles
id | points |
---------------------------
1 | 10 |
2 | 20 |
3 | 0 |
4 | 40 |
pointsCounter
pointsTotal |
--------------
70 |
這是我當前不完整的php代碼:
<?php
include 'db_connect.php';
$sql = "SELECT points FROM profiles";
$result = mysqli_query($mysqli, $sql); //$mysqli is my connection defined in db_connect
if (mysqli_num_rows($result) > 0){
$points = mysqli_fetch_assoc($result);
}
echo $points['pointsTotal'];
這可能最好作為查詢來處理。 使用SUM()
sql函數將查詢中的所有點加在一起,作為“ pointTotal”。 其余代碼應該可以正常工作。
嘗試這個:
$sql = "SELECT SUM(points) AS pointTotal
FROM profiles";
$result = mysqli_query($mysqli, $sql); //$mysqli is my connection defined in db_connect
if (mysqli_num_rows($result) > 0){
$points = mysqli_fetch_assoc($result);
}
echo $points['pointTotal'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.