从SQL查询中获取一行编号

时间:2016-06-29 17:44:10

标签: php mysql

我正在试图弄清楚如何从SQL表中获取一行数。在我的情况下,我需要根据他/她的分数获得用户的排名。我有下面的代码可以做到但是有没有更好的方法在一个查询中帮助这个?

$rank = 0;
$username = $_SESSION['user'];

     $query = "SELECT username, SUM(`score`) as total_score FROM answers GROUP BY username ORDER BY total_score DESC";
       if ($stmt = mysqli_prepare($connect, $query)) {
                mysqli_stmt_bind_param($stmt);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_bind_result($stmt, $uname, $score);
                       while (mysqli_stmt_fetch($stmt)) {
                             $user = $uname;
                             $rank++;
                                  if ($user == $username) {
                                        echo $rank;
                                        break;
                                      }
                               }
                                 mysqli_stmt_close($stmt);
                        } 

1 个答案:

答案 0 :(得分:1)

你可以从你的sql获得排名

SELECT username, SUM(`score`) as total_score,@curRank := @curRank + 1 AS rank FROM answers,(SELECT @curRank := 0) GROUP BY username ORDER BY total_score DESC


example 

select DONATUR,COUNT(DISTINCT AREA) ,@curRank := @curRank + 1 AS rank from funding,(SELECT @curRank := 0) r group by Donatur;
+---------+----------------------+------+
| DONATUR | COUNT(DISTINCT AREA) | rank |
+---------+----------------------+------+
| Mr.X    |                    3 |    1 |
| Mr.Y    |                    1 |    2 |
| Mr.Z    |                    2 |    3 |
+---------+----------------------+------+
3 rows in set (0.00 sec)

如果你想在列表中间只有一个用户,你可以这样做

mysql> select DONATUR,COUNT(DISTINCT AREA) ,@curRank := @curRank + 1 AS rank from funding,(SELECT @curRank := 0) r group by Donatur having DONATUR="Mr.Y";
+---------+----------------------+------+
| DONATUR | COUNT(DISTINCT AREA) | rank |
+---------+----------------------+------+
| Mr.Y    |                    1 |    2 |
+---------+----------------------+------+
1 row in set (0.00 sec)

使用此查询

SELECT @curRank := @curRank + 1 AS rank,username,score from  (select username,COUNT(DISTINCT score) AS score  from answers group by username  order by COUNT(DISTINCT score) ) y,(SELECT @curRank := 0) r where username=?";