Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4 select distinct on multiple columns in postgres with where and limit

How do you select multiple fields with distinct values, and other non-distinct fields with them, all in one call with where and limit? I tried .pluck (which supports multiple fields in rails 4), .uniq (which didn't work in my case).

like image 241
Ryan Avatar asked Oct 15 '14 22:10

Ryan


People also ask

Can we use distinct for multiple columns?

The DISTINCT clause is used in the SELECT statement to remove duplicate rows from a result set. The DISTINCT clause keeps one row for each group of duplicates. The DISTINCT clause can be applied to one or more columns in the select list of the SELECT statement.

How do I SELECT distinct in PostgreSQL?

Removing duplicate rows from a query result set in PostgreSQL can be done using the SELECT statement with the DISTINCT clause. It keeps one row for each group of duplicates. The DISTINCT clause can be used for a single column or for a list of columns.

How can I get distinct values from multiple columns in SQL?

Select with distinct on all columns of the first query. Select with distinct on multiple columns and order by clause. Count() function and select with distinct on multiple columns.

How do you use distinct in the middle of a selected statement?

The DISTINCT clause filters out FULL DUPLICATE ROWS. It goes right after the SELECT keyword, since it applies to the entire row, not single columns. You cannot use it in between columns.


1 Answers

This is what worked for me, when used in the controller action

@models = Model.select('DISTINCT ON (field1,field2,field3) *')
     .where(id: params[:id])
     .limit(100)
like image 116
Ryan Avatar answered Nov 04 '22 04:11

Ryan