Answer the question
In order to leave comments, you need to log in
How to optimize a query for 700,000+ records?
mysql, phpmyadmin, laravel.
$articles = DB::table('articles')->select('articles.*','folders.path','folders.title as parent_title')
->join('folders','folders.id','=','articles.parent_folder_id')
->orderBy('articles.sticked', 'DESC')
->orderby('published_at', 'DESC')
->limit(20)
->get();
// это весь запрос
EXPLAIN
select `slc_articles`.*, `slc_folders`.`path`, `slc_folders`.`title`as `parent_title` from `slc_articles`
inner join `slc_folders` on `slc_folders`.`id` = `slc_articles`.`parent_folder_id`
order by `slc_articles`.`sticked` desc, `published_at` desc
limit 11
offset 0
Answer the question
In order to leave comments, you need to log in
the composite index with the necessary sorting is necessary. Well, in general, the stickiness index is a complicated thing. it's better to make two dates (one to display and one to sort/display sticky on top). Well, or store the sticky id in a separate place and get a list by id + the rest - from those sorted by date with the exception of sticky id. In any case, experiments are needed.
Well, at any cost, remove join from the query, perhaps at the cost of two queries or wrapping the main select in a subquery ( select ... from (select ... order by ... limit 10 ) as subquery inner join ... );
Well, there are 2 variants, as for me
1) Pull out all folders with one request, make its ID a key, cache it, and then go through everything calmly during the cycle. Also, do not forget about updating the cache when updating or inserting new data.
Sometimes logic works faster in PHP than in pure SQL
2) There is also a variant to make another table where you combine all the data of two tables, so to speak, simplify. Also you will make indexes necessary to you. Well, the same problem with updating the data, when updating / inserting, update your new table.
See what else you can cache in the app.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question