如何查找()某些字段中唯一的所有记录?
我有一个“请求”对象列表,每个对象都具有相当正常的活动记录质量。 requests 表通过连接表“games_requests”与 games 表相关,因此请求具有 request.games 数组。
问题是,有没有办法找到最后 n 个唯一请求,其中唯一性由 games 列和其他几个列定义,但专门忽略其他列(例如请求用户的名称?)
我看到了类似于“find (:all, :limit=>5, :include=>[:games,:stage])”的语法,但返回重复项。
谢谢...
编辑:感谢混乱的出色回应。 你让我非常接近,但我仍然需要返回有效的请求对象:请求行中不同的前 5 条记录。 我可以在构建它时使用该查找,然后对表中与第一个查找返回的每个集合相匹配的第一行进行第二次查找。
编辑:
Games.find(
:all, :limit => 5,
:include => [:games, :requests],
:group => 'games, whatever, whatever_else'
)
...给出一个 SQL 错误:
Mysql::Error: Unknown column 'games' in 'group statement': SELECT * FROM `games` GROUP BY games
我对我认为对我的项目正确的内容进行了一些更改; 获取请求列表而不是游戏等:
Request.find(
:all, :order=>"id DESC", :limit=>5,
:include=>[:games], #including requests here generates an sql error
:group=>'games, etc' #mysql error: games isn't an attribute of requests
:conditions=>'etc'
)
我想我将不得不使用 :join=>; 选项在这里。
I have a list of 'request' objects, each of which has fairly normal activerecord qualities. The requests table is related to the games table with a join table, 'games_requests,' so that a request has a request.games array.
The question is, is there a way to do a find for the last n unique requests, where uniqueness is defined by the games column and a couple others, but specifically ignores other colums (like the name of the requesting user?)
I saw a syntax like 'find (:all, :limit=>5, :include=>[:games,:stage])' but that was returning duplicates.
Thanks...
EDIT: Thanks to chaos for a great response. You got me really close, but I still need the returns to be valid request objects: the first 5 records that are distinct in the requested rows. I could just use the find as you constructed it and then do a second find for the first row in the table that matches each of the sets returned by the first find.
EDIT:
Games.find(
:all, :limit => 5,
:include => [:games, :requests],
:group => 'games, whatever, whatever_else'
)
...gives an SQL error:
Mysql::Error: Unknown column 'games' in 'group statement': SELECT * FROM `games` GROUP BY games
I made a few changes for what I assumed to be correct for my project; getting a list of requests instead of games, etc:
Request.find(
:all, :order=>"id DESC", :limit=>5,
:include=>[:games], #including requests here generates an sql error
:group=>'games, etc' #mysql error: games isn't an attribute of requests
:conditions=>'etc'
)
I'm thinking I'm going to have to use the :join=> option here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试 Rails uniq_by。它也可以使用关联并返回数组。
@document = Model.uniq_by(&:field)
更多详细信息
Try Rails uniq_by.It also works with association and returns array.
@document = Model.uniq_by(&:field)
More Detail
我认为您可以使用 find_by_sql 和 GROUP BY 来做到这一点:
I think you'll be able to do this using find_by_sql and GROUP BY: