Rails SELECT与postgres不同

时间:2012-12-11 06:01:47

标签: ruby-on-rails ruby-on-rails-3 postgresql

所以我试图在我的桌子上使用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">]

所以我希望结果在tag列上只是唯一的,但是除非它通过select,否则它不会让我按created_at命令。

2 个答案:

答案 0 :(得分:4)

我认为您要做的是为每个标记选择由最早(即最小)created_at排序的不同标记值。这将是解决由具有多个关联created_at值的标记产生的歧义的一种方法。

如果是这种情况,请尝试以下内容:

Hashlog.select("tag, min(created_at) as earliest").group("tag").order("earliest DESC").limit(10)

答案 1 :(得分:0)

我在项目中使用了以下代码段

Product.select("DISTINCT(products.material_id), products.material_id, products.class_id").where('products.class_id' => current_user.class_id) 
相关问题