下面的代码返回一个包含来自 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/