如何设置MAX和组的变量?

时间:2015-07-24 22:16:19

标签: php mysql syntax group-by max

我在选择SQL Max和组语法时遇到问题,然后将其设置为变量。我选择MAX分数没问题。但我喜欢回应拥有该分数和ID的用户重定向到他的个人资料页面

这是我的数据库

-----------------------------
  id  |  user   |  score | justplayed
   1  | player1 | 1000   | 1
   2  | player2 | 1000   | 0

PHP代码

$sql = "SELECT MAX(score) AS max_score FROM score GROUP BY score WHERE justplayed > 0 ";
    $result = mysqli_query($con, $sql);

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            $highscore = $row["max_score"];
            $highscoreowner = $row["user"];
            $highscoreownerid = $row["id"];
        }
    }

Html代码

Player of the day
<? echo $highscoreowner; ?>
Score
<? echo $highscore; ?><br>
<a href="profile.php?id=<? echo $highscoreownerid; ?>

1 个答案:

答案 0 :(得分:0)

您只是在SQL查询中选择最大分数,因此您无法在PHP中提取其他值。如果您要查找得分最高的整行,请改用此查询:

SELECT score, user, id
FROM score
WHERE justplayed > 0
ORDER BY score DESC
LIMIT 1

这会占用所有行,从最高分到最低分排序,然后只返回第一行。