Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails select distinct

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

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

like image 573
lamrin Avatar asked Dec 21 '22 11:12

lamrin


1 Answers

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

like image 198
keymone Avatar answered Jan 09 '23 22:01

keymone