简体   繁体   English

将SQL查询转换为Rails

[英]translate SQL query into Rails

after searching for a while I found the SQL query that gives me the result I am looking for. 搜索了一会后,我发现了SQL查询,该查询为我提供了所要查找的结果。

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. 我想要的是获取他的服务的最新服务时间,即serviceA,serviceB和serviceC,但只有最新记录。

Now I need to get this query into rails, best into the model into a scope so I can call it again. 现在,我需要将此查询放入rails中,最好将其放入模型中,使其进入作用域,以便再次调用它。 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; 从(SELECT MAX(created_at)作为maxdate,(来自服务GROUP BY服务名的其他列名)中选择*)r INNER JOIN服务t ON t.servicename = r.servicename并且user_id = 1;

i think this will retrieve the newest records ie the services with newest service times . 我认为这将检索最新记录,即具有最新服务时间的服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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