我正在尝试在具有作用域的 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.13
和 Postgres 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/