Mysql Rails应用中SQL查询的形成
我是RubyonRails新手。现在我正在研究Rails应用程序的性能问题。我使用NewRelic rpm来找出代码的瓶颈。在这样做的时候,我发现了一些我无法理解的东西。问题在于,在我的Rails应用程序中,我使用了两个模型A、B和C,其中模型B有两个属性:A的主键和C的主键,如下所示:Mysql Rails应用中SQL查询的形成,mysql,ruby-on-rails,datamapper,newrelic-platform,Mysql,Ruby On Rails,Datamapper,Newrelic Platform,我是RubyonRails新手。现在我正在研究Rails应用程序的性能问题。我使用NewRelic rpm来找出代码的瓶颈。在这样做的时候,我发现了一些我无法理解的东西。问题在于,在我的Rails应用程序中,我使用了两个模型A、B和C,其中模型B有两个属性:A的主键和C的主键,如下所示: class B include DataMapper::Resource belongs_to :A, :key=>true belongs_to :C, :key=>true end
class B
include DataMapper::Resource
belongs_to :A, :key=>true
belongs_to :C, :key=>true
end
A的型号如下:
class A
include DataMapper::Resource
property :prop1
...
has n, :bs
has n, :cs, :through => :bs
end
在发出以下语句a.find(:c.id=>10)时,它在内部执行以下SQL查询:
select a.prop1, a.prop2,... from a INNER JOIN b on a.id = b.a_id INNER JOIN c on b.c_id = c.id where (c.id=10) GROUP BY a.prop1, a.prop2,....[here in group by all the properties that has been mentioned in select appears, I don't know why]
在web事务期间,此语句占用了太多的时间。有趣的是,当我在终端的mysql提示符中执行相同的自动生成查询时,所花费的时间非常少。我想这是因为在group by子句中提到了这么多字段。我无法理解查询是如何形成的。如果有人愿意帮助我解决这个问题并优化它,我将非常感激。谢谢。我想您已经正确配置了模型关联,如下所示:
class A < ActiveRecord
has_many :B
has_many :C, through: :B
end
class B < ActiveRecord
belongs_to :A
belongs_to :C
end
class C < ActiveRecord
has_many :B
has_many :A, through: :B
end
这样您将获得更好的性能。我已经在使用DataMapper了。我不能用ActiveRecord重写它,因为这将是太多的工作。如果您在DataMapper中有任何解决方案,请建议。
a.c.find(10) #mind the plural forms though