From 26455d0efb085c82a3040a61d825f17b329a28bf Mon Sep 17 00:00:00 2001 From: p31729568 Date: Sat, 27 Apr 2019 11:20:12 +0800 Subject: [PATCH] add index to fix order slow issue --- app/services/management/school_data_contrast_service.rb | 8 +++----- .../20190427025209_add_index_to_school_daily_reports.rb | 9 +++++++++ 2 files changed, 12 insertions(+), 5 deletions(-) create mode 100644 db/migrate/20190427025209_add_index_to_school_daily_reports.rb diff --git a/app/services/management/school_data_contrast_service.rb b/app/services/management/school_data_contrast_service.rb index 9390e46f..47c7f117 100644 --- a/app/services/management/school_data_contrast_service.rb +++ b/app/services/management/school_data_contrast_service.rb @@ -24,10 +24,8 @@ class Management::SchoolDataContrastService reports = reports.where("school_name LIKE :keyword OR school_id LIKE :keyword", keyword: "%#{keyword}%") end - reports = reports.group(:school_id) - count = reports.count.count - - reports = reports.limit(PAGE_SIZE).offset(offset) + count = reports.count('distinct(school_id)') + reports = reports.group(:school_id).limit(PAGE_SIZE).offset(offset) [count, reports] end @@ -56,7 +54,7 @@ class Management::SchoolDataContrastService end def select_columns - "school_id, school_name,"\ + "school_id, school_name, @total:=0, @other_total:=0,"\ "(@total:=SUM(IF(date BETWEEN '#{format_date(params[:begin_date])}' AND '#{format_date(params[:end_date])}', #{contrast_column}, 0))) total,"\ "(@other_total:=SUM(IF(date BETWEEN '#{format_date(params[:other_begin_date])}' AND '#{format_date(params[:other_end_date])}', #{contrast_column}, 0))) other_total,"\ "(IF(@other_total - @total = 0, 0.0, round((@other_total - @total) / IF(@total = 0, 1, @total), 5))) percentage,"\ diff --git a/db/migrate/20190427025209_add_index_to_school_daily_reports.rb b/db/migrate/20190427025209_add_index_to_school_daily_reports.rb new file mode 100644 index 00000000..5cfc2796 --- /dev/null +++ b/db/migrate/20190427025209_add_index_to_school_daily_reports.rb @@ -0,0 +1,9 @@ +class AddIndexToSchoolDailyReports < ActiveRecord::Migration + def change + add_index :school_daily_reports, [:date, :teacher_increase_count] + add_index :school_daily_reports, [:date, :student_increase_count] + add_index :school_daily_reports, [:date, :course_increase_count] + add_index :school_daily_reports, [:date, :shixun_increase_count] + add_index :school_daily_reports, [:date, :active_user_count] + end +end