tags:

views:

386

answers:

3

I've spent quite a lot of time today trying various things, but none of them seem to work. Here's my situation, I'd like to be able to select the rank of a row based on it's ID from a specifically sorted row

For example, if my query is something like:

SELECT id, name FROM people ORDER BY name ASC

with results like:

id   name
3    Andrew
1    Bob
5    Joe
4    John
2    Steve

I would like to get the rank (what row it ends up in the results) without returning all the rows and looping throw them until I get to the one I want (in PHP).

For example, I'd like to select the 'rank' of 'Steve' so that it returns -- in this case -- 5 (not his id, but the 'rank' of his name in the above query).

Similarly, I'd like to be able to select the rank of whatever row has the ID of 1. For this example, I'd like to return a 'rank' of 2 (because that's in what result row there is an ID of 1) and nothing else.

I've Google'd as much as I could with varying results... either having really slow queries for larger tables or having to create all sorts of temporary tables and user variables (the former I'd REALLY like to avoid, the latter I suppose I can live with).

Any help or insight would be greatly appreciated.

+1  A: 

Something like this?

SELECT Row, id, name
FROM (SELECT @row := @row + 1 AS Row, id, name
      FROM people
      ORDER BY name ASC)
WHERE Row = @SomeRowNumber

If you want to go by the ID, just alter the where clause.

Brandon
A: 

Try this:

SELECT @rownum:=@rownum+1 `rank`, p.id, p.name
FROM people p, (SELECT @rownum:=0) r
ORDER BY name ASC
Plutor
This is like what I had previously come up with Googling, and it works great if I want the 'rank' of every row within my table, but what if I want only the rank of a single row?I tried something like<pre>SELECT @rownum:=@rownum+1 `rank`, p.id, p.nameFROM people p, (SELECT @rownum:=0) rWHERE id = 5ORDER BY name ASC</pre>But this will always give me a rank of 1 (because it only ever returns one result). Is there a way to get the single rank of a single row based on the entire query results?I hope this makes sense.
theotherlight
A: 

from artfulsoftware:

SELECT p1.id, p1.name, COUNT( p2.name ) AS Rank
    FROM people p1
    JOIN people p2 
    ON p1.name < p2.name
    OR (
         p1.name = p2.name
         AND p1.id = p2.id
    )
GROUP BY p1.id, p1.name
ORDER BY p1.name DESC , p1.id DESC
LIMIT 4,1
bjelli
After a few small changes this does seem to work pretty darn well for what I need. However, one additional complication: would it be possible to select a set of rows given a set of conditions (such as, only people that have a 'J' in their name -- WHERE name LIKE '%j%'. I tried this, and while the result field 'rank' is still relevant, it skips numbers for those that don't have a J in the name. Thoughts?
theotherlight