Index of a record in a sorted relations
Given I have a sorted relation (perhaps done by
SELECT id
FROM model
WHERE type = 'a'
ORDER BY name`
...), now I want to quickly get the index of a specific record e.g record id#15003.
How should I do it in 开发者_Python百科MySql [I'm a Rails developer]?
Assuming by index you mean row number. That is, if the results come back '1, 7, 9,...' then the "index of 9" is 3, it is the third row.
You want what are variously called "Window functions" or "statistical functions" like row_number().
MySQL doesn't have them. Sorry.
However, though I'm not a RAILS developer, I have to assume you can get results in an array and search the array and return an index number?
EDIT: Based on your comment to Brad's answer, if you are doing this for the sake of paginating results, then look at the LIMIT and OFFSET. http://dev.mysql.com/doc/refman/5.0/en/select.html
Are you looking for something such as this: http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/
I believe this is going to require you to select all results up to your desired result. So, if your record is at index 15003, you must select records 1-15003. Obviously this is not efficient or scalable... Perhaps there is a better way to approach the problem? Why do you need the index anyway? Why not place a more restrictive WHERE condition on the original SQL?
精彩评论