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).
commentsat once and then select them by some parts. It can be there 1000 comments or 10k... – 0101 Dec 22 '14 at 22:58cache_tablethe same structure ascomments? – RolandoMySQLDBA Dec 22 '14 at 23:05UPDATE 2014-12-22 18:19 EST? Is it possible to somehow eliminate the use of a temporary table? – 0101 Dec 23 '14 at 17:45UPDATE 2014-12-23 13:08 EST, I think we still don't understand each other. Let's say that at the same time a get 3 request ,so 3 different users and 3 different connections with 3 temp tables. After data is selected or moved to cache the connection terminate and tmp is dropped. Next time (if there is some data in cache) I will select the data directly (probably) using a different connection that will be taken from the pool. Anyway, do you think it is stable-secure enough to use temp tables in this way? May it cause some problems in the future? Thanks a lot – 0101 Dec 23 '14 at 18:23