php - 计算用户的排名

标签 php mysql sql codeigniter ranking

我想使用 MySQL 计算排名。我有一个名为结果的表

result_id    test_id    exam_id    user_id    percentage
   1            5          6          50          57
   2            5          6          58          76 
   3            5          6          65          42

我想根据用户的 user_id 和 test_id 计算用户的排名,例如 user_id(58) 有 1 排名 user_id(50) 有 2 等等

我尝试过查询

select percentage  from result where test_id=$test_id(i.e 5) and user_id=$user_id(i.e 58)

但它给出了 76 并且没有给出排名

我也尝试过

select percentage from result where test_id=$test_id(i.e 5) 

但它给了我 57,76,42

有什么方法可以计算用户的排名吗?

最佳答案

您可以简单地使用ORDER BY百分比DESC。试试这个...

$con = mysqli_connect("host","user","password","db_name");
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'SELECT * FROM result ORDER BY percentage DESC';
$result = mysqli_query( $con, $sql );
if (!mysqli_query($con, $sql)) {
    die('Error: '. mysqli_error($con));
}
$i = 1;
while($row = mysqli_fetch_array($result)) {
    echo 'User ID ' . $row['user_id'] . ' has rank  ' . $i . ' and percentage ' . $row['percentage'] . '</br>';
    $i++;
}
mysql_close($con);

关于php - 计算用户的排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25580723/

相关文章:

php - 如何在 MySQL 中创建一个值自动增加的列

php - Apache 和 mysql 端口

php - 如何通过 URL 参数将 Javascript/jQuery 数组发送到 PHP?

java - MySQL插入然后更新表数据

php - 我想从3个不同的txt文件中获取数据,然后随机显示数据

PHP - 检查数组的所有元素是否都在字符串中

mysql - 加入 mysql 存储过程

sql - 如何在 SQL Server 2008 中创建宽表?它的使用限制是什么?

sql - 基于引用记录的自定义排序

MySQL OUTER LEFT JOIN 性能