MySQL UPDATE列的值和旧值的ADD新值

时间:2014-03-28 00:30:10

标签: php html mysql

我有一个页面显示已在系统中注册的所有用户的排行榜分数,该分数存储在我的数据库中。

表1

Points_hisotry表:

| points_id || user_id(fk) || point_hist |
|___________||_____________||____________|
|      1    ||     10      ||    100     |  
|___________||_____________||____________|
|      2    ||     11      ||     30     |
|___________||_____________||____________|
|      3    ||     11      ||     70     |
|___________||_____________||____________|
|      4    ||     11      ||    200     |

表2

Users表:

| 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这应该加起来300。

我需要一个查询来帮助我加入这个表,然后将相同users_id的行加到一个并将其打印在我的记分板上。

我已经尝试了很多查询,但我没有做对。

以下是来自 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"];

以上查询是打印出上述两个表格中的所有username及其点数。

我是新手,所以我需要一些帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用SUM()对它们进行总结(他们已经考虑过了),但是您需要通过GROUP BY告诉SQL要汇总哪些行以及哪些行应该&#&# 39;吨

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

应该做的伎俩