From 09d7a697bf77b206e130c3dc7ced6b88ebfdc16b Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Fri, 1 Aug 2014 13:09:16 -0400 Subject: [PATCH] OPTIMIZATION: Add index to `post_timings` and adjust the query --- app/models/user_stat.rb | 7 +++---- .../20140801170444_create_post_timings_user_index.rb | 5 +++++ 2 files changed, 8 insertions(+), 4 deletions(-) create mode 100644 db/migrate/20140801170444_create_post_timings_user_index.rb diff --git a/app/models/user_stat.rb b/app/models/user_stat.rb index 82bf4245062..5453db91086 100644 --- a/app/models/user_stat.rb +++ b/app/models/user_stat.rb @@ -30,10 +30,9 @@ class UserStat < ActiveRecord::Base FROM (SELECT pt.user_id, COUNT(*) AS c - FROM post_timings AS pt - WHERE pt.user_id IN ( - SELECT u1.id FROM users u1 where u1.last_seen_at > :seen_at - ) + FROM users AS u + INNER JOIN post_timings AS pt ON pt.user_id = u.id + WHERE u.last_seen_at > :seen_at GROUP BY pt.user_id) AS X WHERE X.user_id = user_stats.user_id AND X.c <> posts_read_count diff --git a/db/migrate/20140801170444_create_post_timings_user_index.rb b/db/migrate/20140801170444_create_post_timings_user_index.rb new file mode 100644 index 00000000000..c33b84f862b --- /dev/null +++ b/db/migrate/20140801170444_create_post_timings_user_index.rb @@ -0,0 +1,5 @@ +class CreatePostTimingsUserIndex < ActiveRecord::Migration + def change + add_index :post_timings, :user_id + end +end