Rails Activerecord 关系:使用子查询作为 SQL 选择语句的表

编程入门 行业动态 更新时间:2024-10-27 23:30:42
本文介绍了Rails Activerecord 关系:使用子查询作为 SQL 选择语句的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

谁能帮我弄清楚如何使用 Rails(我使用 Rails 4)Activerecord 方法编写以下 SQL?我知道你可以用 find_by_sql 做到这一点,但我想保留活动记录关系.这是我正在尝试创建的 postGreSQL 数据库的 sql:

Can somebody help me figure out how to write the following SQL using Rails (I'm using Rails 4) Activerecord methods? I know you can do this with find_by_sql but I'd like to preserve the active record relation. Here's the sql for a postGreSQL db that I'm trying to create:

SELECT * FROM (SELECT DISTINCT ON(table_a.id) table_a.name as alias_a, table_b.id, table_b.time FROM table_1 LEFT OUTER JOIN table_b ON table_a.id = table_b.id ORDER BY table_a.id, table_b.time asc) AS subquery ORDER BY alias_a asc

对于我的子查询,我有以下内容(生成上面子查询的 sql):

For my subquery, I have the following (which generates the sql of the subquery above):

@subquery = table_a.select("DISTINCT ON(table_a.id) table_a.name as alias_a, table_b.time") @subquery = @subquery.joins("LEFT OUTER JOIN table_b ON table_a.id = table_b.id") @subquery = @subquery.order("table_a.id, table_b.time asc")

但是,我不知道如何编写使用@subquery 作为外部 select 语句表的 select 语句.

But, I can't figure out how to write a select statement that uses @subquery as the table for the outer select statement.

推荐答案

使用 Active Record 接口中的 from() 方法.

Use the from() method from the Active Record interface.

例如:

@subquery = table_a.select("DISTINCT ON(table_a.id) table_a.name as alias_a, table_b.time") @subquery = @subquery.joins("LEFT OUTER JOIN table_b ON table_a.id = table_b.id") @subquery = @subquery.order("table_a.id, table_b.time asc")

然后在外部查询中像这样使用它:

Then use it like this in the outer query:

@query = OtherModel.from("(#{@subquery.to_sql}) table_name, other_model_table, etc ...").where(:field => table_name.alias_a) ...etc.

更多推荐

Rails Activerecord 关系:使用子查询作为 SQL 选择语句的表

本文发布于:2023-10-22 08:07:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1516940.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   关系   Rails   Activerecord   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!