Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row position in MYSQL query [duplicate]

Tags:

sql

mysql

Possible Duplicate:
ROW_NUMBER() in MySQL

Is this possible? I want to get a bunch of results in a specific order and then find out the position of a row by its id, for example:

1, foo
2, bar
3, foobar

I want to get the position of 1 in Alphabetical order, it would return 2

like image 312
Jake Avatar asked Aug 14 '11 15:08

Jake


People also ask

How can I find the duplicate row counts from a specific table in MySQL?

Find Duplicate Row values in One ColumnSELECT col, COUNT(col) FROM table_name GROUP BY col HAVING COUNT(col) > 1; In the above query, we do a GROUP BY for the column for which we want to check duplicates. We also use a COUNT() and HAVING clause to get the row counts for each group.


2 Answers

SELECT id, name, rank FROM 
    (
    SELECT t.id, t.name,
        @rownum := @rownum + 1 AS rank
    FROM TABLE t, (SELECT @rownum := 0) r
    ORDER BY name ASC
    ) `selection` WHERE id=1

Modified from this answer >> ROW_NUMBER() in MySQL

like image 86
potNPan Avatar answered Sep 30 '22 19:09

potNPan


Working answer (in MySQL):

If you have the following table "names":

+------+--------+
| id   | name   |
+------+--------+
|    1 | foo    |
|    2 | bar    |
|    3 | foobar |
+------+--------+

And you want to know where "foo" ranks alphabetically, then:

SELECT z.rank FROM (
    SELECT t.id, t.name, @rownum := @rownum + 1 AS rank
    FROM names t, (SELECT @rownum := 0) r
    ORDER BY name ASC
) as z WHERE id=1;

Will produce:

+------+
| rank |
+------+
|    2 |
+------+

The changes from @potNpan's solution are the addition of as z and the change from @rownum = @rownum + 1 to @rownum := @rownum + 1. Now it works :)

like image 45
Robin Winslow Avatar answered Sep 30 '22 21:09

Robin Winslow