[英]How to get unique records from Active Record rails 4 based on a column
[英]How to get unique record by special column from a where method with Rails?
例如,此方法返回記錄為:
Post.where(valid: true)
# [
[0] #<Post:11113892841> { :id => 1, :valid => 1, :user_id => 1},
[1] #<Post:21113892841> { :id => 2, :valid => 1, :user_id => 2},
[2] #<Post:31113892841> { :id => 3, :valid => 1, :user_id => 2},
[3] #<Post:41113892841> { :id => 4, :valid => 1, :user_id => 3},
...
]
想要僅獲得唯一的user_id
記錄為:
[
[0] #<Post:11113892841> { :id => 1, :valid => 1, :user_id => 1},
[1] #<Post:21113892841> { :id => 2, :valid => 1, :user_id => 2},
[2] #<Post:41113892841> { :id => 4, :valid => 1, :user_id => 3},
...
]
怎么做?
最可靠的方法是:
Post.where(valid: true).select('distinct(user_id)')
雖然可以使用.distinct
但這只會返回user_id列:
irb(main):037:0> Post.select(:user_id).distinct
Post Load (0.6ms) SELECT DISTINCT "posts"."user_id" FROM "posts" LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Post id: nil, user_id: 1>]>
這是沒有用的,因為您實際上無法對結果集做任何事情。
不幸的是,由於SQL標准的解釋方式不同,因此沒有一個針對此相對簡單問題的好的多語言解決方案。
在MySQL上,您可以使用GROUP BY語句:
Post.group(:user_id)
但是,這不適用於Postgres 。 ( column "posts.id" must appear in the GROUP BY clause
)。 您可能會說,它在MySQL上起作用的唯一原因是它允許潛在的歧義查詢-它不符合SQL 1999或2003標准。
在Postgres上,您應該改用DISTICT ON(user_id)
因為它不允許上面的查詢:
irb(main):058:0> Post.select("DISTINCT ON (posts.user_id) posts.*")
Post Load (0.9ms) SELECT DISTINCT ON (posts.user_id) posts.* FROM "posts" LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Post id: 3, user_id: 1, created_at: "2018-09-14 11:46:12", updated_at: "2018-09-14 11:46:12">]>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.