Answer the question
In order to leave comments, you need to log in
What is the best way to sort a relatively large query on another table?
Short query:
SELECT ideas.id, ideas.foo, ideas.bar FROM ideas
WHERE aaa=bbb AND ... AND ... AND ...
AND ideas.id IN (SELECT idea_id FROM ideas_tags WHERE tag_name = 'tag_from_subscriptions')
AND ideas.id NOT IN (SELECT idea_id FROM ideas_tags WHERE tag_name = 'tag_from_hs')
ORDER BY ideas.id DESC
LIMIT 10
Now the task is to sort elements not by id, but by modification date. The problem is that for this, the server looks at all ideas in general, sorts, and then filters the result, while this is not in the original request and it stops after it has typed the required number of rows.
I tried to make a separate table, which contains only the id of the ideas and the id of the record, which determines their order.
Replaced ORDER BY ideas.id DESC with ORDER BY (SELECT id FROM ideas_index WHERE ideas_index.idea_id = ideas.id) DESC. The request, of course, began to be executed not 0.008 seconds, but 0.2-0.7 in difficult cases.
How can such sorting be implemented without a significant loss of performance? There are about 50 thousand records in the table.
Answer the question
In order to leave comments, you need to log in
As already mentioned above - index
+ does not hurt to replace in (select) with inner join
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question