php - 向我的 mySQL 输出数据添加排名

标签 php html mysql

下面的代码返回一个包含来自 mysql 的数据的表,但我在输出中缺少的是一个生成的列,该列的排名基于列的数据(本例中为 Wilks)。我寻找了类似问题的示例和答案,但无法使其发挥作用。

简而言之:我需要在 ID 列旁边添加一个额外的列,根据 Wilks 列中的数据显示从 1 开始的排名。

非常感谢!

<?php
$con=mysqli_connect("localhost", "user", "password", "dbname");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM `Mannen` ORDER BY `Wilks` DESC");

echo "<table border='1'>
<tr>
<th>#</th>
<th>Naam</th>
<th>Lichaamsgewicht</th>
<th>Vereniging</th>
<th>Squat</th>
<th>Bench</th>
<th>Deadlift</th>
<th>Totaal</th>
<th>Wilks</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" . $row['ID'] . "</td>";
    echo "<td>" . $row['Naam'] . "</td>";
    echo "<td>" . $row['Lichaamsgewicht'] . "</td>";
    echo "<td>" . $row['Vereniging'] . "</td>";
    echo "<td>" . $row['Squat'] . "</td>";
    echo "<td>" . $row['Bench'] . "</td>";
    echo "<td>" . $row['Deadlift'] . "</td>";
    echo "<td>" . $row['Totaal'] . "</td>";
    echo "<td>" . $row['Wilks'] . "</td>";
    echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

最佳答案

首先,如果您只想要一个枚举值,您可以使用 PHP 获取它。

但是,在 MySQL 中使用变量就足够简单了:

SELECT m.*, (@rn := @rn + 1) as rank
FROM Mannen m CROSS JOIN
     (SELECT @rn := 0) params
ORDER BY Lichaamsgewicht DESC;

从技术上讲,这实现了 row_number() 的相关函数,而不是 rank()。您的问题不清楚“排名”的含义。

关于php - 向我的 mySQL 输出数据添加排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39681539/

相关文章:

php - 使用 PHP 进行 USPS 费率计算器的 XML 请求和响应

html - 删除列表左侧的空格 <li>

使用变量作为表名的mysql错误

mysql - 防火墙后面的.NET SQL 查询身份验证

php - Nginx/php 查询字符串

php - 使用 PHP 从 HEIC 照片中读取 EXIF 数据

javascript - 单击 href 和单击复选框时选中复选框

php - 为每个不同的行选择计数(mysql 和 php)

php - 将多数组从模型传递到 Controller

jquery - 如何在 html 和 css 中将 div 居中,始终保持纵横比,并填充最大屏幕宽度/高度?