我有一个页面,显示所有已在系统中注册的用户的排行榜分数,该分数存储在我的数据库中。
表 1:
Points_hisotry
表:
| points_id || user_id(fk) || point_hist |
|___________||_____________||____________|
| 1 || 10 || 100 |
|___________||_____________||____________|
| 2 || 11 || 30 |
|___________||_____________||____________|
| 3 || 11 || 70 |
|___________||_____________||____________|
| 4 || 11 || 200 |
表 2:
用户
表:
| users_id || username || firstname || lastname ||
|__________||___________||____________||__________||
| 10 || alan1 || Alan || Smith ||
|__________||___________||____________||__________||
| 11 || Jaz12 || Jass || Hopal ||
|__________||___________||____________||__________||
| 12 || Shubs || shubs || hawash ||
|__________||___________||____________||__________||
| 13 || John || Rob || engli ||
在 points_history
表中,我有 3 行具有相同的 users_id
,我需要将它们相加,以便最终得到总 Point_hist
users_id
的 code> 总计应为 300。
我需要一个查询来帮助我连接这些表,然后将相同 users_id
的行求和为 1,并将其打印在我的记分板上。
我尝试了很多查询,但都没有得到正确的结果。
以下是我从 leaderboard.php 获取的一些 PHP 代码:
$sql = "SELECT * FROM users, points_history WHERE users.users_id = points_history.users_id";
$user_query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$username = $row ["username"];
$point_hist = $row["point_hist"];
上面的查询是打印出上面两个表中的所有用户名
及其积分。
我是新手,所以我需要一些帮助。
最佳答案
您可以使用 SUM()
对它们进行求和(谁会想到),但您需要通过 GROUP BY
告诉 SQL 对哪些行进行求和这是不应该的。
SELECT users.*, SUM(points_history.point_hist) AS total_points
FROM users
INNER JOIN points_history
ON users.users_id = points_history.users_id
GROUP BY users_id
应该可以解决问题
关于php - MySQL UPDATE 列的值并用旧值添加新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22701989/