铁轨和Postgres - 具有计数列的查询真的这么复杂吗?

发布于 2024-10-04 08:43:26 字数 799 浏览 1 评论 0原文

我的应用程序中有以下模型(仅显示相关范围):

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

段念尘 2024-10-11 08:43:26

也许您可以使用 ActiveRecord :counter_cache 从完全不同的角度解决问题?例如,

belongs_to :application, :counter_cache => true

您可以通过这种方式进行简短、简单且高性能的查询。

Maybe you could approach the problem from a completely different angle by using the ActiveRecord :counter_cache ? e.g.

belongs_to :application, :counter_cache => true

You could maybe have a short, simple and performant query this way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文