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
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.
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
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With