[英]Rails SELECT Distinct with postgres
So I am trying to use the SELECT Distinct option on my table 所以我想在我的桌子上使用SELECT Distinct选项
Hashlog.select("DISTINCT tag").select("created_at").order("created_at DESC").limit(10)
1.9.3-p286 :017 > Hashlog.select("DISTINCT tag").select("created_at").order("created_at DESC").limit(10)
Hashlog Load (0.7ms) SELECT DISTINCT tag, created_at FROM "hashlogs" ORDER BY created_at DESC LIMIT 10
=> [#<Hashlog tag: "new", created_at: "2012-12-11 04:06:37">,
#<Hashlog tag: "now", created_at: "2012-12-11 04:06:33">,
#<Hashlog tag: "googleold", created_at: "2012-12-11 04:06:28">,
#<Hashlog tag: "google", created_at: "2012-12-11 04:06:26">,
#<Hashlog tag: "facebook", created_at: "2012-12-11 04:06:21">,
#<Hashlog tag: "facebook", created_at: "2012-12-11 04:06:18">,
#<Hashlog tag: "faceboot", created_at: "2012-12-11 04:06:15">]
So I want the results to only unique on the tag column, but it will not let me order by created_at unless its passed through the select. 所以我希望结果只在标记列上唯一,但它不会让我按created_at排序,除非它通过select。
I think what you're trying to do is select distinct tag values ordered by the earliest (ie smallest) created_at
for each tag. 我认为你要做的是为每个标签选择最早 (即最小)
created_at
排序的不同标签值。 That would be one way to resolve the ambiguity resulting from a tag with multiple associated created_at
values. 这将是解决由具有多个关联的
created_at
值的标记导致的歧义的一种方法。
If that's the case, try something like the following: 如果是这种情况,请尝试以下方法:
Hashlog.select("tag, min(created_at) as earliest").group("tag").order("earliest DESC").limit(10)
. 。
我在我的项目中使用了以下代码段
Product.select("DISTINCT(products.material_id), products.material_id, products.class_id").where('products.class_id' => current_user.class_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.