【问题标题】:Sort MySQL query in PHP在 PHP 中对 MySQL 查询进行排序
【发布时间】:2020-03-28 15:47:15
【问题描述】:

我正在尝试按降序(最高优先)对不同用户的“积分”进行排序。但目前查询是按照用户 ID 的顺序返回的(它们出现在数据库中的顺序)。我不确定我的代码有什么问题?

用户可以在多个联赛中,因此它首先查询以查看特定用户所在的联赛。通过联赛 ID,我查询以查看每个联赛中的用户。然后我查询每个用户在该联赛中的总分。最终,我想获得每个联赛的用户排名,但目前按积分排序的查询不起作用。

图像显示了点是如何出现的。 “1635”是登录的用户积分。对于第一个联赛,我试图显示“排名 2”。

// SQL query to see what leagues user is in
    $query = mysqli_query($con, "SELECT * FROM UserLeague WHERE UserID='$userid'");
    $num = mysqli_num_rows($query);

    if($num == 0) {
      echo 'You are not in any leagues';
      return;
    } else {
      echo '<div class="pleague-table">';
      echo '<div class="pleague-table-header">';
      echo '<p>PRIVATE LEAGUE</p>';
      echo '<p>CURRENT RANK</p>';
      echo '</div>';
    }

    while($leagueid = mysqli_fetch_assoc($query)) {

        $lid = $leagueid['LeagueID'];

        // Get all league info that user is in

        $query2 = mysqli_query($con, "SELECT * FROM League WHERE LeagueID='$lid'");

        // Get all users that is in each league

        $queryposition = mysqli_query($con, "SELECT UserID FROM UserLeague WHERE LeagueID='$lid'");

        while($getpoints = mysqli_fetch_assoc($queryposition)) {

          $uid = $getpoints['UserID'];

          // Get each users points in each league

          $querypoints = mysqli_query($con, "SELECT * FROM Points WHERE UserID='$uid' ORDER BY total DESC");
          while($row = mysqli_fetch_assoc($querypoints)) {
            echo $row['total']. '</br>';
          }


        }



        while($leaguename = mysqli_fetch_assoc($query2)) {
          echo '<div class="league-link">';
          echo $leaguename['Name'];
          echo '<a href="#">Options</a>';
          echo '</div>';
        }

    }
'''

【问题讨论】:

标签: php mysql sql ranking


【解决方案1】:

您正在尝试组合 2 个表:UserLeague 和 Points,以从 UserLeague 中选择用户并按 Points 对他们进行排序。对于这种情况,SQL 中有 JOIN 语法:

SELECT Points.* 
FROM Points 
RIGHT JOIN UserLeague ON Points.UserID=UserLeague.UserID 
WHERE UserLeague.LeagueID=? 
ORDER BY Points.total DESC

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 1970-01-01
    • 2017-04-05
    • 2021-11-24
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多