ruby-on-rails - 在事件记录范围内的 select 语句中添加 DISTINCT ON

标签 ruby-on-rails postgresql activerecord distinct-on

我正在尝试在具有作用域的 rails 中使用 distinct on,我在我的模型中创建了一个这样的方法:

def self.fetch_most_recent_by_user(scope)
  scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) user_id, eld_logs.guid").order("user_id, eld_logs.created_at desc").map(&:guid))
end

当我执行此操作时,出现如下错误:

TestModel.fetch_most_recent_by_user(TestModel.includes(:user))

ERROR:  syntax error at or near "DISTINCT"
LINE 1: SELECT guid, DISTINCT ON (user_id) user_id...

在搜索 DISTINCT ON 时,我发现它应该是 postgres 使其工作的选择语句中的第一个元素。

我想在 select 语句中添加 DISTINCT ON。我尝试使用从 here 获得的 except(:select) 清除旧的 select 语句, 但它不起作用,因为 includes(:user) 在执行左连接时首先添加用户属性。

我正在使用 Rails 4.0.13Postgres 9.4.12。感谢您的帮助。

最佳答案

我发现如果 include 干扰了 distinct 我的子查询,因为 DISTINCT ON 失败了。我对此修改了我的方法并且它有效:

  def self.fetch_most_recent_eld_log_by_user(scope, include_associations = { })
    scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) eld_logs.user_id, eld_logs.guid").order("eld_logs.user_id, eld_logs.created_at desc").map(&:guid))
        .includes(include_associations)
  end

如果有人可以提供一种方法在事件记录范围的选择语句中预先添加一些内容,那将是一件好事。

关于ruby-on-rails - 在事件记录范围内的 select 语句中添加 DISTINCT ON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994628/

相关文章:

ruby-on-rails - 用于临时应用程序与生产应用程序的不同 S3 存储桶

sql - 查找与列关联最密切的其他行

sql - PostgreSQL utf8 字符比较

mysql查询在几行上查找满足条件的id

ruby-on-rails - Activeadmin:如何过滤匹配两个或多个搜索词的字符串

mysql - 在 Rails 中重构已填充的 SQL 数据库

ruby-on-rails - will_paginate 路由仅适用于 > 1 页

ruby-on-rails - rails : Render view content in post-processor (model/helper issues)

mysql - SQL 查询、Rails View 、删除小数位

postgresql - 将 Oracle upsert 转换为 PostgreSQL 准备好的语句