php - 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'];
解决方案
这可能最好作为查询处理。使用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'];
推荐阅读
- python - 如何找到容器的 docker 镜像?
- html - 如何通过代码使用 ng-options 更改选择中的值?
- java - 有没有办法为我的主要活动设置条件?
- api - Go Daddy API 的 PowerShell Invoke-WebRequest 错误
- c# - 如何在 .restext 资源条目中保留前导或尾随空格?
- python - 对模型类的 __init__ 方法的更改似乎没有生效
- javascript - 如何将 GLSL 比例和位置与 VideoContext 一起使用?
- java - 我如何在 Java 中验证日期(仅当前日期或之后)
- jquery - 关于 Laravel Webpack Mix 和提取方法
- r - R - dplyr 中的代码行运行时间