Activerecord:优化select * from table query

时间:2014-04-28 08:49:13

标签: sql ruby-on-rails activerecord indexing

所以我有countriesregions的表格分别包含274和3953行:不是很多。

每次我显示带有地址的表单时,我都会运行Country.allRegion.all将其放入下拉列表中以填写地址表单。

每次我获得EXPLAIN

  EXPLAIN (0.4ms)  EXPLAIN SELECT "countries".* FROM "countries" ORDER BY name ASC
EXPLAIN for: SELECT "countries".* FROM "countries"  ORDER BY name ASC
                             QUERY PLAN
--------------------------------------------------------------------
 Sort  (cost=23.83..24.52 rows=274 width=678)
   Sort Key: name
   ->  Seq Scan on countries  (cost=0.00..12.74 rows=274 width=678)
(3 rows)

  Region Load (37.8ms)  SELECT "regions".* FROM "regions" ORDER BY name ASC
  EXPLAIN (0.9ms)  EXPLAIN SELECT "regions".* FROM "regions" ORDER BY name ASC
EXPLAIN for: SELECT "regions".* FROM "regions"  ORDER BY name ASC
                            QUERY PLAN
------------------------------------------------------------------
 Sort  (cost=323.70..333.58 rows=3953 width=48)
   Sort Key: name
   ->  Seq Scan on regions  (cost=0.00..87.53 rows=3953 width=48)
(3 rows)

显然我需要优化这些查询。但我不知道该怎么做。

  • 是否会添加索引帮助?根据我的理解,索引可以快速获取特定数据,但此处查询为select * from <table>

  • 我该怎么办?

以下是我创建表格的迁移,以防它有用:

  def change
    create_table :countries do |t|
      t.string :name, :limit => 50, :null => false
      t.string :fips104, :limit => 2, :null => false
      t.string :iso2, :limit => 2, :null => false
      t.string :iso3, :limit => 3, :null => false
      t.string :ison, :limit => 4, :null => false
      t.string :internet, :limit => 2, :null => false
      t.string :capital, :limit => 25
      t.string :map_reference, :limit => 50
      t.string :nationality_singular, :limit => 35
      t.string :nationality_plural, :limit => 35
      t.string :currency, :limit => 30
      t.string :currency_code, :limit => 3
      t.integer :population
      t.string :title, :limit => 50
      t.string :comment, :limit => 255

      t.timestamps
    end

  create_table :regions do |t|
     t.references :country, :null => false
     t.string :name, :limit => 45, :null => false
     t.string :code, :limit => 8, :null => false
     t.string :adm1code, :limit => 4, :null => false
     t.float :tax_rate

     t.timestamps
  end

end

提前致谢

0 个答案:

没有答案