简体   繁体   中英

Get position of each row based on ORDER

I have a highscore table that has three columns, name, highScore, rep. Currently I loop through the results ORDERED by rep. I have an $i est within the loop and this displays as rank eg:

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++;
            }
        }

Currently this works without fault. The problem is that i have now implemened a "sort by" button which changes the SQL to ORDER to highScore instead of rep . the only problem is that the Rank does not match now. Is there a way of getting and echoing the position of each row based on rep and then seslcting and ordering based on highScore ?

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 contains your rank by rep and the table is ordered by highscore now.

Can you try this,

       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++;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM