【问题标题】:Concatenate (glue) where conditions by OR or AND (Arel, Rails3)通过 OR 或 AND 连接(胶水)条件(Arel,Rails3)
【发布时间】:2010-11-06 06:26:54
【问题描述】:

我有几个复杂查询(使用子查询等...)并且想用 OR 或 AND 语句将它们粘合在一起。

例如:

where1=table.where(...)
where2=table.where(...)

我想要类似的东西

where3=where1.or where2

下一个例子对我不起作用:

users.where(users[:name].eq('bob').or(users[:age].lt(25)))

因为我有几个 where(..) 查询,我想连接 它们

换句话说

我有 3 种方法:首先返回第一个位置,第二个第二个,第三个 - 或连接。

我必须能够在我的应用程序中使用所有 3 种方法并保存 DRY 代码

【问题讨论】:

    标签: sql ruby-on-rails subquery where arel


    【解决方案1】:

    您在寻找表格吗:

    users.where(users[:name].eq('bob').or(users[:age].lt(25)))
    

    文档:https://github.com/rails/arel

    【讨论】:

      【解决方案2】:

      users.where(users[:name].eq('bob').or(users[:age].lt(25))) 很接近,但您需要获取 arel_table 来指定列,例如

      t = User.arel_table
      User.where(t[:name].eq('bob').or(t[:age].lt(25)))
      

      【讨论】:

        【解决方案3】:

        我知道对于 AND 连接,您可以这样做:

        users = User.where(:name => 'jack')
        users = users.where(:job => 'developer')
        

        然后你会在 SQL 中使用 AND 进行连接(尝试在末尾使用 #to_sql

        除此之外你可以做的:

        where1=table.where(...)
        where2=table.where(...)
        where1 & where2
        

        示例:

        (User.where(:name => 'jack') & User.where(:job => 'dev')).to_sql
        => "SELECT `users`.* FROM `users` WHERE `users`.`name` = 'jack' AND `users`.`job` = 'dev'" 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-20
          • 2011-02-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-20
          • 1970-01-01
          相关资源
          最近更新 更多