簡體   English   中英

導軌 select 不同

[英]Rails select distinct

在一個場景中,我想檢索具有不同值的記錄,所以我為此使用了 distinct,

Book.where(["user_id =?",@user_id]).select('distinct title_id')

 `this, only retrives the records like this [#<Book title_id: 30>, #<Book title_id: 31> ]`

但我想獲取 Book 的 id 以及 title_id

所以,請告訴我如何處理這個

謝謝

使用分組:

Book.where(:user_id => @user.id).grouped('title_id')

問題是,如果您進行分組,則不能有不同的圖書 ID,它們都被分組到單行中。 您可以使用 GROUP_CONCAT 來解決此問題:

Book...select('books.*, GROUP_CONCAT(id) as ids')

這樣,您將擁有每個組的 book ids屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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