From fcfce3e426a64ffa567c572eeeaeb2ef700b15dc Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 15 Jan 2018 16:38:58 +1100 Subject: [PATCH] PERF: avoid expensive OR clause query info more efficiently --- lib/topic_query.rb | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/topic_query.rb b/lib/topic_query.rb index 3dae7132e09..2d27044739b 100644 --- a/lib/topic_query.rb +++ b/lib/topic_query.rb @@ -512,7 +512,17 @@ class TopicQuery if options[:no_subcategories] result = result.where('categories.id = ?', category_id) else - result = result.where('categories.id = :category_id OR (categories.parent_category_id = :category_id AND categories.topic_id <> topics.id)', category_id: category_id) + sql = <<~SQL + categories.id IN ( + SELECT c2.id FROM categories c2 WHERE c2.parent_category_id = :category_id + UNION ALL + SELECT :category_id + ) AND + topics.id NOT IN ( + SELECT c3.topic_id FROM categories c3 WHERE c3.parent_category_id = :category_id + ) + SQL + result = result.where(sql, category_id: category_id) end result = result.references(:categories)