【问题标题】:Activerecord method for "as" - Derived Alias“as”的 Activerecord 方法 - 派生别名
【发布时间】:2011-03-11 00:41:56
【问题描述】:

我正在尝试使用 ActiveRecord 方法构建 SQL 查询。该查询有一些需要派生表的连接,如下所示:

(SELECT voteable_id, COUNT(vote) FROM votes WHERE vote = 0 GROUP BY voteable_id) AS example

我的问题是我似乎找不到可以为派生表创建别名的方法(此处:AS 示例)。因此,我的问题是,是否可以使用 activerecord 方法构建这样的查询?

编辑:只是为了让它更清楚。我有以下方法来构建 select 语句。

t = Vote # Vote being the table name
t = t.where("vote = 0")
t = t.group("voteable_id")
t.select("voteable_id, COUNT(vote)")

但是我将如何添加“AS”别名?

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 orm activerecord


    【解决方案1】:

    你总是可以使用#to_sql的结果:

    t = Vote # Vote being the table name
    t = t.where("vote = 0")
    t = t.group("voteable_id")
    sql = t.select("voteable_id, COUNT(vote)").to_sql
    t.connection.find_by_sql("(#{sql}) AS example")
    

    真正的问题是为什么你需要使用别名。回答这个问题,我们会更好地为您提供帮助。

    【讨论】:

    • 我使用别名的真正原因是因为这个派生表是一个更大的查询的一部分,它被加入到这个查询中。没有别名,据我所知,它不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多