I am working on pagination for a complex join query and unfortunately I am not sure what's the best way to go... Right now I am thinking about the following solution.
Imagine that SELECT id...
is the complex join query. I copy all id's to the temporary cache.
CREATE TEMPORARY TABLE tmp SELECT id FROM comments WHERE user_id = 123;
Now I will check number of selected records.
SELECT COUNT(*) FROM tmp;
If a number of records is let's say greater than 1000 all records will be moved to a cache table and then selected by e.g 100's (completely all records from a cache are going to be selected ,so it is not as a classic pagination...).
INSERT INTO cache_table SELECT * FROM tmp;
DROP TEMPORARY TABLE tmp; #Temp is not needed anymore
however if number of records is smaller than 1000 then they don't have to be cached and can be immediately selected:
SELECT column_names FROM comments c JOIN tmp t ON c.id = t.id;
DROP TEMPORARY TABLE tmp; #Temp is not needed anymore
OK, now if there are some records in cache, they will be selected by 100 in this case. Records don't have to be selected all at once (10*100), a connection may close and client will ask data later. So we have got 1000 records in cache. To select a data I execute:
SELECT column_names FROM comments c JOIN cache_table ct ON c.id = ct.id LIMIT 100;
DELETE FROM cache_table LIMIT 100; #Records are selected so they can be deleted
This process is repeated until it return 0 or less than 100 records (If there is e.g 1001 rec).