简体   繁体   中英

how to get records from table with uniq on two columns - rails

I'm trying to fetch records from database that should be uniqued by two attributes example

id name value

1 dog 4

2 dog 4

3 cat 5

4 cat 4

I want the result to be

id name value

1 dog 4

3 cat 5

4 cat 4

so the data has been uniqued by value and name , I've tried many ways with ruby to do but with no luck

You can use group by :

select min(id) as id, name, value
from table t
group by name, value;

it worked with group method of rails

table.all.group('value, name') 

the generated query is

select * from table t group by value, name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM