Jump to content

Determining Position in Query


Stryves

Recommended Posts

I'm trying to determine what place someone is based on a query.

 

<?php 

Query is "SELECT clientname, sales FROM clients ORDER BY sales DESC"

$i=1;
while($query)
{
if($query['clientname']==$_POST['clientname'])
{
  $clientrank=$i;
  }
  i++;
}
?>

 

Is there any easier way to do this?

Link to comment
https://forums.phpfreaks.com/topic/157841-determining-position-in-query/
Share on other sites

This would work, although I dunno if I'd recommend it for super large tables:

SELECT clientname, sales, (SELECT count(*) + 1 FROM clients WHERE sales > c.sales) as position FROM clients as c ORDER BY sales DESC

 

Run that in a query, and then when looping through the results it will tell you the position of each person

 

Also, you can add in a WHERE `clientname`='NAMEHERE' to show one result, with position:

SELECT clientname, sales, (SELECT count(*) + 1 FROM clients WHERE sales > c.sales) as position FROM clients as c WHERE clientname = 'bob' ORDER BY sales DESC

The query is is running, from top sales down.

 

$i=1

 

when the while is running, if the client name is not the current result, i increments, and then the while runs again.

 

If the clientname is matched during the 5th run through the while, the $clientrank = 5.

 

This way I'd know they are 5th best in sales.

 

This would work, although I dunno if I'd recommend it for super large tables:

 

 

Haha, that was my concern as well... I was using the i++ increment to determine the position, but it's always better to make the DB do the work.

 

My other solution was creating a table for results, and cron job it to run/refresh every night... Just have static results per day.

 

I wasn't sure if there was an easier way to do this... Guess not :)

Take a look at my post above - with the query. For large tables, I mean like hundreds of thousands of rows. I doubt you have that many rows in there. I have a few DB's that have over 900k rows and can still run pretty complex queries quickly. Its just a matter of testing and tweaking it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.