选择具有最高值的整行结果

时间:2016-04-29 10:43:57

标签: php mysql mysqli

我有一个非常简单的问题,但遗憾的是我无法自己解决这个问题。我有一个包含12个玩家的列表,这些玩家都有(唯一的)ID,等级,属性1和属性4。我只想要具有最高评级的玩家的行,然后是attribute1然后是attribute4。因此它首先必须对评级进行排序,如果有2个评级为84,SQL将检查attribute1等。这是我的代码。

$sql = "SELECT * FROM `players_db` WHERE `id` = $player[0] OR `id` = $player[1] OR `id` = $player[2] OR `id` = $player[3] OR `id` = $player[4] OR `id` = $player[5] OR `id` = $player[6] OR `id` = $player[7] OR `id` = $player[8] OR `id` = $player[9] OR `id` = $player[10] OR `id` = $player[11] ORDER BY `rating` DESC , `attribute1` DESC, `attribute4` DESC";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['rating'];
echo '<br>';
}

我无法弄清楚如何更进一步,因为我已经尝试了

  

SELECT MAX(&#39; rating&#39;)FROM players_db WHERE ...

但是它只获得了最高玩家的评分,那么如何获得评分最高的玩家的整行,然后是attribute1和attribute4?

我希望有人可以帮助我!谢谢!

2 个答案:

答案 0 :(得分:1)

此查询将提供与评分最高的玩家对应的记录。如果出现平局,attribute1attribute4将用于按顺序打破平局。

SELECT *
FROM players_db
ORDER BY rating DESC, attribute1 DESC, attribute4 DESC
LIMIT 1

答案 1 :(得分:0)

使用$sql = "SELECT * FROM `players_db` WHERE `id` = $player[0] OR `id` = $player[1] OR `id` = $player[2] OR `id` = $player[3] OR `id` = $player[4] OR `id` = $player[5] OR `id` = $player[6] OR `id` = $player[7] OR `id` = $player[8] OR `id` = $player[9] OR `id` = $player[10] OR `id` = $player[11] ORDER BY `rating` DESC , `attribute1` DESC, `attribute4` DESC LIMIT 1"; $result = $conn->query($sql); while ($row = mysqli_fetch_assoc($result)) { echo $row['rating']; echo '<br>'; } ,首先它会按评分对记录进行排序,然后它会选择使用顶级AS的第一行{{1}}:

{{1}}