Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql paginated results, find "page" for specific result

I have an application using a MySql database which is displaying a paginated list of records, to which to which the user is able to add new ones. I know how to get paginated results using LIMIT etc, but the question is how to go a specific page when adding a new record. If the page size is 20, and the user is viewing the first page, and they add a record which is 23rd (out of say 100), how do we determine which page to show the user.

So, essentially, given a page size and a specific record, how do I determine which "page" to show out of the pages. The total pages do NOT include all of the records for the table they belong to, but the criteria for getting them is static.


Edit: I should have been more specific. The records contain a unique ID field and a string name field. The resultant records are sorted by the name alphabetically. Also, this is a java application.

The only thing I can think of is to select all the desired records sorted by name and then some how find the position in those results of the specific record. From that position the page number could be easily calculated since we know the page size, but I'm not sure if they is MySql syntax for getting the position of a record in the results.

The "dumb" solution would be to just grab them all and then in the application code (java), determine the specific records position in all the results. But is seems like their must be a more efficient way.

like image 871
KurToMe Avatar asked Jan 31 '12 20:01

KurToMe


1 Answers

SELECT COUNT(*) as CNT FROM tbl WHERE name < (SELECT name FROM tbl WHERE id = 42)

After that you just divide CNT value to the amount rows per page and round (Math.floor()) it

Or you can even do that in sql:

SELECT FLOOR(COUNT(*) / 20) AS page_number ...
like image 161
zerkms Avatar answered Nov 03 '22 22:11

zerkms