Jump to content

Recommended Posts

Thanks for the help if you can with my little problem below.

 

I really have no idea how do create this query in MySQL.

 

What I want to do:

 

Order table so that the greatest 'score' is at the top of the table. Find the position of X id in that table

 

Any help. appreciated...

 

Link to comment
https://forums.phpfreaks.com/topic/122258-how-can-i-do-this-with-mysql/
Share on other sites

I follow you on the first part, but lost you on the second part.

 

select * from table_name order by `score` desc

 

or maybe you mean:

 

select * from table_name where `id` = 'x' order by `score` desc  # Assuming multiple rows returned

 

 

Be a bit more clear when posting. Thanks.

 

 

Ok, let me re-explain XD

 

Say we had this table:

 

id    score

1        5

2        8

3        16

4        25

5        4

 

I want MySQL to re-order the table so it looks like this:

 

id    score

4        25

3        16

2        8

1        5

5        4

 

Then, say I wanted to know the "rank" or id 1, i would like to have mysql query to find how far down from the top it is, so the position of 1, would be 4th, or 4

 

Thanks if you can help.

// run the query: select * from table_name order by `score` desc

// check for errors

 

$rank = 0;

while ($row = mysql_fetch_array($result)) {

    $rank++;  // adds 1

    echo 'Rank: ', $rank, ' Score: ', $row['score']; // put HTML break to end line

}

 

Just put an 'if' before the echo of which ID you want to display. Example:

 

$id_looking_for = 1;

 

// run the query: select * from table_name order by `score` desc

// check for errors

 

$rank = 0;

while ($row = mysql_fetch_array($result)) {

    $rank++;  // adds 1

    if ($id_looking_for == $row['id']) {

        echo 'Rank: ', $rank, ' Score: ', $row['score']; // put HTML break to end line

        break;  // get out of loop

    }

}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.