简体   繁体   English

将 SQL 语句转换为 Arel Rails 查询

[英]Convert SQL statement to Arel Rails query

So, let's get straight: I'm struggling to days do convert this SQL Statement:所以,让我们直截了当地说:我正在努力转换这个 SQL 语句:

select * from (
    select distinct on (program_id) editions.*, programs.* 
    from editions inner join programs on editions.program_id = programs.id 
    where programs.station_id = 1) as editionsprograms 
order by fixed desc, published_at desc, time desc 
limit 4;

to an Arel rails query.到 Arel rails 查询。 Someone has any idea about how could make an Arel query that would have the same effect of the above SQL?有人知道如何进行与上述 SQL 具有相同效果的 Arel 查询?

You can use the from method to accomplish the tricky part of your query (selecting from a subquery).您可以使用from方法来完成查询的棘手部分(从子查询中选择)。 The subquery itself should be a straightforward mapping ( select , joins , where , etc).子查询本身应该是一个简单的映射( selectjoinswhere等)。 So the result would be something like this:所以结果会是这样的:

Edition.select('*')
.from(
  Editions.select('DISTINCT ON (program_id) editions.*, programs.*')
          .joins(:programs)
          .where(programs: { station_id: 1 })
)
.order(fixed: :desc, published_at: :desc, time: :desc)
.limit(4)

This will return Edition records, with additional data from the Program record stored on each.这将返回版本记录,以及存储在每个版本记录中的程序记录中的附加数据。 To avoid the weirdness of that result type, which may also just throw errors and be unable to resolve, you could either use Arel directly (similar syntax) or use .pluck on the end to pluck only the columns you actually need.为了避免该结果类型的怪异,它也可能只是抛出错误并且无法解决,您可以直接使用 Arel(类似语法)或在末尾使用.pluck.pluck您实际需要的列。

Recently I found this cool project http://www.scuttle.io/最近我发现了这个很酷的项目http://www.scuttle.io/
scuttle - sql 到 arel 转换器

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

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