I wrote a SQL query (below) that selects the next 25 records after the record with postID 201. (You don't have to read it)
SELECT
title,
content,
table_with_rn.userID,
table_with_rn.username,
postID,
post_timestamp
FROM
(
SELECT
title,
content,
posts.userID,
users.username,
postID,
post_timestamp,
@rownum := @rownum + 1 AS row_number2
FROM
(
posts
INNER JOIN users ON posts.userID = users.userID
)
CROSS JOIN(
SELECT
@rownum := 0
) AS r
ORDER BY
post_timestamp
DESC
) AS table_with_rn
WHERE
row_number2 >(
SELECT
row_number
FROM
(
SELECT
postID,
@rownum := @rownum + 1 AS row_number
FROM
(
posts
INNER JOIN users ON posts.userID = users.userID
)
CROSS JOIN(
SELECT
@rownum := 0
) AS r
ORDER BY
post_timestamp
DESC
) AS twn
WHERE
postID = 201
)
LIMIT 25
It sorts the table and then creates a column that holds the row number of each row. It then select the row number of the record with the specific postID, before selecting the records with greater row numbers from a duplicate table.
This query works fine, but it seems very complicated for a task that sounds rather simple. Is there a better/more efficient/simpler way of doing it?
Note: I realise I could skip the whole row_number thing and just use postID, since it is incremental, but I would like to keep my options open if I ever decide I don't want my pk to be an integer any more.
Note2: This is MySQL.