繁体   English   中英

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM