PERF: Prefer subquery instead of two queries (#25167)

The query that is now a subquery could return a long list of category
IDs, which slowed down the query considerably. This improvement reduces
the execution time from over 2 seconds down to about 100ms.
This commit is contained in:
Bianca Nenciu 2024-01-09 02:19:37 +02:00 committed by GitHub
parent 8c6144d116
commit be46acce8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -58,10 +58,9 @@ class CategoryList
if SiteSetting.fixed_category_positions
categories.order(:position, :id)
else
allowed_category_ids = categories.pluck(:id) << nil # `nil` is necessary to include categories without any associated topics
categories
.left_outer_joins(:featured_topics)
.where(topics: { category_id: allowed_category_ids })
.where("topics.category_id IS NULL OR topics.category_id IN (?)", categories.select(:id))
.group("categories.id")
.order("max(topics.bumped_at) DESC NULLS LAST")
.order("categories.id ASC")