From 0c302c7aea1c122d7e54f54b6cbbcf3fcd16e48a Mon Sep 17 00:00:00 2001 From: yanxd Date: Thu, 15 May 2014 13:53:06 +0800 Subject: [PATCH] 1s ===> 0.005s --- app/controllers/school_controller.rb | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/app/controllers/school_controller.rb b/app/controllers/school_controller.rb index f0f5dd70..ec14ba5c 100644 --- a/app/controllers/school_controller.rb +++ b/app/controllers/school_controller.rb @@ -47,10 +47,14 @@ class SchoolController < ApplicationController options << "" end - # 查询已添加用户的学校 - schools_arr = UserExtensions.where("school_id IS NOT NULL").pluck(:school_id).uniq # 取id取学校名 - school = School.where(id: schools_arr).select("id, name") + # 连接子表: 查询已添加用户的学校 + school = School.select("id, name"). + joins("RIGHT JOIN ( + SELECT DISTINCT school_id + FROM #{UserExtensions.table_name} + WHERE school_id IS NOT NULL) AS sids ON schools.id = sids.school_id"). + where("#{School.table_name}.id IS NOT NULL") options_s = "" school.each do |s|