【问题标题】:How can I generate a select from an aliased table in Arel?如何从 Arel 中的别名表中生成选择?
【发布时间】:2018-02-18 05:58:22
【问题描述】:

我需要使用带有表单的 Arel 生成 SQL

SELECT c2.user_id, MAX(c2.created_at) as max_created_at
FROM comments AS c2
GROUP BY c2.user_id

在更大的查询中用作子查询

SELECT *
FROM comments
INNER JOIN (...subquery...) s1
ON comments.user_id = s1.user_id
AND comments.created_at = s1.max_created_at

我不知道如何在子查询中为comments 表设置别名。

我能得到的最接近的是

c2 = Comment.arel_table.alias
s1 = Comment.arel_table.project(
    c2[:user_id], c2[:created_at].maximum.as('max_created_at')
    ).group('user_id').as('s1')

但这会生成不正确的 SQL

SELECT c2.user_id, MAX(c2.created_at) as max_created_at
FROM comments
GROUP BY c2.user_id

(由于未定义 c2 导致的错误)

生成不带别名的查询会导致不正确的结果,因为子查询内外的表名发生冲突。

这给出了Arel::TableAliasproject 方法的错误。

s1 = c2.project(...

如何使用 Arel 查询别名表?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord arel


    【解决方案1】:

    您可以使用from 告诉它要从哪个表(或在本例中为表别名)进行投影:

    c2 = Comment.arel_table.alias
    s1 = Comment.arel_table.
      project(c2[:user_id], c2[:created_at].maximum.as('max_created_at')).
      from(c2).group('user_id').as('s1')
    puts s1.to_sql
    # (SELECT "comments_2"."user_id", MAX("comments_2"."created_at") AS max_created_at
    #  FROM "comments" "comments_2" GROUP BY user_id) s1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多