Ruby-on-rails 如何 find() 在某些字段中唯一的所有记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/651181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find() all records unique in certain fields?
提问by Sniggerfardimungus
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.
我有一个“请求”对象列表,每个对象都具有相当正常的 activerecord 质量。requests 表通过连接表“games_requests”与游戏表相关联,因此请求具有 request.games 数组。
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?)
问题是,有没有办法对最后 n 个唯一请求进行查找,其中唯一性由 games 列和其他几个定义,但特别忽略其他列(例如请求用户的姓名?)
I saw a syntax like 'find (:all, :limit=>5, :include=>[:games,:stage])' but that was returning duplicates.
我看到了类似 'find (:all, :limit=>5, :include=>[:games,:stage])' 的语法,但它返回了重复项。
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.
编辑:感谢混乱的伟大回应。你让我非常接近,但我仍然需要返回是有效的请求对象:请求的行中不同的前 5 条记录。我可以在您构建它时使用查找,然后对表中与第一个查找返回的每个集合相匹配的第一行进行第二次查找。
EDIT:
编辑:
Games.find(
:all, :limit => 5,
:include => [:games, :requests],
:group => 'games, whatever, whatever_else'
)
...gives an SQL error:
...给出一个 SQL 错误:
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.
我想我将不得不在这里使用 :join=> 选项。
采纳答案by chaos
Games.find(
:all, :limit => 5,
:include => [:games, :requests],
:group => 'games, whatever, whatever_else'
)
回答by imsinu9
回答by Codebeef
I think you'll be able to do this using find_by_sql and GROUP BY:
我认为你可以使用 find_by_sql 和 GROUP BY 来做到这一点:
Games.find_by_sql("SELECT * FROM games GROUP BY user_id")

