My challenge is that I have a table of e.g. posts in a forum and I want to get the offset for LIMIT clause right.
To illustrate the example: Table Post - please remember OFFSET is the number/index of the row.
OFFSET 0: ID = 17, AUTHOR = ABC, CREATE_DATE = 2011-05-01
OFFSET 1: ID = 39, AUTHOR = ABC, CREATE_DATE = 2011-05-02
OFFSET 2: ID = 77, AUTHOR = ABC, CREATE_DATE = 2011-05-03
OFFSET 3: ID = 78, AUTHOR = ABC, CREATE_DATE = 2011-05-04
OFFSET 4: ID = 99, AUTHOR = ABC, CREATE_DATE = 2011-05-05
OFFSET 5: ID = 33, AUTHOR = ABC, CREATE_DATE = 2011-05-06
OFFSET 6: ID = 45, AUTHOR = ABC, CREATE_DATE = 2011-05-07
OFFSET 7: ID = 11, AUTHOR = ABC, CREATE_DATE = 2011-05-08
OFFSET 8: ID = 13, AUTHOR = ABC, CREATE_DATE = 2011-05-0开发者_C百科9
OFFSET 9: ID = 88, AUTHOR = ABC, CREATE_DATE = 2011-05-10
Now I want to make query for ID = 45, and my pagination should give a result of 5 entries per page.
SELECT Table.* FROM Table WHERE Table.id = 45 ORDER BY Table.create_date;
Result is one row with ID = 45. And then I want to know that the offset is 6 in relation to the 10 entries in total in the table. I want 5 rows per page, so x = 5 for the following statement.
In other words I know the the row with offset = 6 is on the 2nd page of the results page with 5 entries per page.
SELECT Table.* FROM Table LIMIT x, 5
How do I know x?
My first idea is that I fetch all IDs from the table and just look for the right ID and then divide the offset by 5.
Question: Is there a better way to do this in SQL because to me this seems like a very common challenge?
Bonus question: SQL solution is fine; how to do it in MySQL specifically if there is a difference?
You're usually better off wrapping the whole thing in a transaction with multiple queries. Pseudocode:
select count(*) from table
where create_date <= (select create_date from table where id = 45);
select table.* from table order by create_date limit 5 offset :offset;
精彩评论