首页 > 解决方案 > MySQL从一列计算整数值的总和并将结果存储在另一个表中

问题描述

我首先要说我是 mysql 新手,在这里我没有找到任何问题的答案,也无法自己重新制作其他示例。

我有一个名为“配置文件”的表,用于存储我的用户,其中一列是存储整数的“点”。

我有一个名为“pointsCounter”的第二个表,其中只有一列“pointsTotal”(也是整数),它只存储站点上每个用户的积分。

我想总结“profiles”中的每个用户“points”,并将结果存储在“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'];

标签: phpmysql

解决方案


这可能最好作为查询处理。使用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'];

推荐阅读