簡體   English   中英

Rails SELECT與postgres不同

[英]Rails SELECT Distinct with postgres

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

所以我希望結果只在標記列上唯一,但它不會讓我按created_at排序,除非它通過select。

我認為你要做的是為每個標簽選擇最早 (即最小) created_at排序的不同標簽值。 這將是解決由具有多個關聯的created_at值的標記導致的歧義的一種方法。

如果是這種情況,請嘗試以下方法:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM