铁轨和Postgres - 具有计数列的查询真的这么复杂吗?
我的应用程序中有以下模型(仅显示相关范围):
class Audition < ActiveRecord::Base
def self.with_new_applications
columns = self.column_names.map{|c| "auditions.#{c}" }.join(', ')
select(columns).joins(:applications).merge(Application.unreplied).group(columns)
end
end
class Application < ActiveRecord::Base
def self.unreplied
columns = Application.column_names.map{|c| "applications.#{c}" }.join(', ')
select("#{columns}, count(messages.id) as message_count").
joins('left outer join messages on messages.application_id = applications.id').
group(columns).
having('count(messages.id) = 0')
end
end
由于使用 postgreSQL,与 MySQL 相比,由于需要包含计数列/分组的所有列,查询似乎变得不必要地复杂。
我错过了什么吗?对我来说,它看起来不太“像 Rails”。
这些查询可以以更简单的方式执行吗?
谢谢
I have the following models in my app (only showing the related scopes):
class Audition < ActiveRecord::Base
def self.with_new_applications
columns = self.column_names.map{|c| "auditions.#{c}" }.join(', ')
select(columns).joins(:applications).merge(Application.unreplied).group(columns)
end
end
class Application < ActiveRecord::Base
def self.unreplied
columns = Application.column_names.map{|c| "applications.#{c}" }.join(', ')
select("#{columns}, count(messages.id) as message_count").
joins('left outer join messages on messages.application_id = applications.id').
group(columns).
having('count(messages.id) = 0')
end
end
Due to using postgreSQL it seems like the queries have been made unnecessarily complex when compared to MySQL due to the need to include all the columns for the count columns/grouping.
Am I missing something? It doesn't seem very "Rails-like" to me.
Could these queries be executed in a simpler manner?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您可以使用 ActiveRecord :counter_cache 从完全不同的角度解决问题?例如,
您可以通过这种方式进行简短、简单且高性能的查询。
Maybe you could approach the problem from a completely different angle by using the ActiveRecord :counter_cache ? e.g.
You could maybe have a short, simple and performant query this way.