PHPology is a collective of highly skilled, award winning, web gurus.
Contact Raj on 07985 467 213 or email [email protected]

MYSQL - get rank position of users in database table

On project I am working on it requires me to let the user know what position they are ranked amongst other users with their bid that have assigned to a product. 

Example being there are 10 bids assigned to a Sony Playstation and when the user signs on I need to inform them that they are in position 'x'.

In my case, the lower the bid the lower the rank they are. So it is up to the seller to reduce his product bid in order to sell it.

Rather than show the user a table of rankings, I just wanted a single row mainly to say you are in rank 'x'.

Here is the query I used in my situation:
select
pb.bid_id, pb.product_id, pb.seller_id, pb.bid_price, (select count(1) as num from tbl_products_bid pb2 where pb2.bid_price < pb.bid_price and pb2.product_id = 3) + 1 as rank
from tbl_products_bid as pb
where
pb.product_id = 3 and
pb.seller_id = 1
order by rank asc

If I was to display a ranking guide against this product only i.e. show me top 10 who has the lowest bid then the query would be something like this (basically removed the pb.seller_id = 3): 
select 
pb.bid_id, pb.product_id, pb.seller_id, pb.bid_price, (select count(1) as num from tbl_products_bid pb2 where pb2.bid_price < pb.bid_price and pb2.product_id = 3) + 1 as rank 
from tbl_products_bid as pb 
where 
pb.product_id = 3
order by rank asc

##Note##:
The  pb2.bid_price < pb.bid_price part of the query basically gets me the price based on the lowest first where as  pb2.bid_price > pb.bid_price would get me the results where the price is higher and rank accordingly.

This type of query would work similar to getting results from a highscores table.