I have a paginated list of articles that needs to be sorted by rank but when an article has position <> 0 then it must be inserted in that specific position. I thought that I can at least have the articles with the correct position extracted for the current page and then sort them in PHP to show then in the proper position. I want to do this in MySQL with only one query
Some of my attempts are:
This query tries to select first the articles that have the correct position for the current page and then articles with the highest rank
SELECT id, rank_score, position
FROM Articles
ORDER BY ((position <= (50 * 1)) AND (position > 50 * (1-1))) DESC, rank_score DESC
LIMIT 0, 50
50 is the number of articles displayed on page and 1 is the current page number, they are added on query generation.
This query has the problem that on page 2 the results are wrong because by adding LIMIT 50,50 you can go beyond the articles that have a position on that page.
Another attempt:
SELECT (
SELECT id, rank_score, position
FROM Articles
ORDER BY ((position <= (50 * 1)) AND (position > 50 * (1-1))) DESC, rank_score DESC
LIMIT 50)
UNION (
SELECT id, rank_score, position
FROM Articles
ORDER BY rank_score DESC LIMIT x)
To work correctly the second query must have a limit equal to the number of rows returned from the first query. Plus, anytime an article that has a very high rank that but also a very high position it will be shown earlier because position is ignored in the second query.