I\'m looking for a way to sequentially number rows in a result set (not a table). In essence, I\'m starting with a query like the following:
SELECT
One idea that is pretty inefficient but is ANSI SQL would be to count the number of rows with a lesser id matching the same criteria. I haven't tested this SQL and it probably won't work, but something like:
SELECT id, name, sub.lcount
FROM people outer
JOIN (SELECT id, COUNT(id) lcount FROM people WHERE name = 'Spiewak' AND id < outer.id GROUP BY id) sub on outer.id = sub.id
WHERE name = 'Spiewak'
SELECT @i:=@i+1 AS iterator, t.*
FROM tablename t,(SELECT @i:=0) foo
I know this is an old thread, but I was just now looking for this answer. I tried Dan Goldstein's query in MySQL, but it didn't work as written because 'outer' is a reserved word. Then, I noticed that it is still using a sub-query, anyways.
So, I figured out a version using JOIN, but NO sub-query:
SELECT SUM(IF(p1.id > p2.id, 0, 1)) AS `row`, p2.id, p2.name
FROM people p1 JOIN people p2 ON p1.name = p2.name
WHERE p1.name = 'Spiewak'
GROUP BY p2.id
This worked for me in MySQL 5.1. For MySQL, it seems to be enough to GROUP BY p2.id. An explicit ORDER BY p2.id can be added to the end of the query, but I got the same results, either way.
This page should give you a standard SQL way of doing it:
https://www.sqlteam.com/articles/returning-a-row-number-in-a-query
Hope this helps.
For SQL server, check out the RANK function.
AFAIK, there's no "standard" way.
MS SQL Server has row_number(), which MySQL has not.
The simplest way to do this in MySQL is
SELECT a.*, @num := @num + 1 b from test a, (SELECT @num := 0) d;
Source: comments in http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/