简体   繁体   中英

translate SQL query into Rails

after searching for a while I found the SQL query that gives me the result I am looking for.

select * from (select * from services WHERE user_id=1 ORDER BY created_at DESC) AS x GROUP BY servicename

so a user has many services with different servicenames and servicetimes. ie. a service can be in the list multiple times with different servicetimes. What I wanted was getting the newest servicetimes for his services ie, serviceA, serviceB and serviceC but only the newest records.

Now I need to get this query into rails, best into the model into a scope so I can call it again. Whats the best practice for that? ie I couldnt find a solution how to get the inner select working in rails.

I already did some searching but couldnt find a similar problem.

thanks for any help

select * from (SELECT MAX(created_at) as maxdate,(other coloumn names) from services GROUP BY servicename) r INNER JOIN services t ON t.servicename = r.servicename and user_id=1;

i think this will retrieve the newest records ie the services with newest service times .

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