根据ORDER获取每一行的位置

时间:2014-01-19 16:55:57

标签: php mysql sql mysqli

我有一个高分表,有三列,name,highScore,rep。目前我通过rep循环结果ORDERED。我在循环中有一个$ i est,这显示为排名例如:

SELECT highScore, name, rep FROM  table1 ORDER BY rep DESC

while ($row = $result->fetch_assoc()) 
        {
                echo "<tr>";
                echo "<td>" . $i . "</td>"; // rank
                echo "<td>" . $row["name"] . "</td>"; // name
                echo "<td>" . $row["rep"] . "</td>"; // rep
                echo "<td>" . $row["highScore"] . "</td>"; // high score
                echo "</tr>";
                $i++;
            }
        }

目前这种方法无故障。问题是我现在已经实现了一个“排序依据”按钮,它将SQL更改为ORDER而不是highScore而不是rep。唯一的问题是Rank现在不匹配。有没有办法根据rep获取并回显每行的位置,然后基于highScore进行选择和排序?

2 个答案:

答案 0 :(得分:2)

select * from 
(
  SELECT highScore, name, rep, @rank := @rank + 1 as rank 
  FROM table1, (select @rank := 0) r
  ORDER BY rep DESC
) alias_name
order by highscore desc

rank包含rep的排名,表格现在按highscore排序。

答案 1 :(得分:0)

你能试试吗,

       SELECT highScore, name, rep,pos FROM 
        (
        SELECT t.name, @rownum := @rownum + 1 AS pos
        FROM `table1` t, (SELECT @rownum := 0) r
        ORDER BY t.rep DESC) `table1` 

    while ($row = $result->fetch_assoc()) 
    {
            echo "<tr>";
            echo "<td>" . $i . "</td>"; // rank
            echo "<td>" . $row["name"] . "</td>"; // name
            echo "<td>" . $row["rep"] . "</td>"; // rep
            echo "<td>" . $row["highScore"] . "</td>"; // high score
            echo "<td>" . $row["pos"] . "</td>"; // position
            echo "</tr>";
            $i++;
        }