开发者

Rails select distinct

开发者 https://www.devze.com 2023-03-19 22:16 出处:网络
in a scenario i want to retrieve the records with different values so i used distinct for that, 开发者_StackOverflow中文版

in a scenario i want to retrieve the records with different values so i used distinct for that,

开发者_StackOverflow中文版

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> ]`

but i want to fetch the id of Book as well along with title_id

so, please advise me how to work on this

thanks


use grouping:

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

problem is that if you do grouping you can't have different book ids, they are all grouped into single row. You can use GROUP_CONCAT to workaround that:

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

that way you'll have book ids attribute for every group

0

精彩评论

暂无评论...
验证码 换一张
取 消