【问题标题】:How to combine two conditions in a where clause?如何在where子句中组合两个条件?
【发布时间】:2012-05-16 03:57:23
【问题描述】:

我有以下几点:

time_range = (1.month.ago.beginning_of_month..1.month.ago.end_of_month)

Comment.where(:created_at => time_range).count

如何在 where 子句中添加如下语句:

.where("user_id is not in (?)",[user_ids]).

如何将两者结合起来?谢谢

【问题讨论】:

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


    【解决方案1】:

    如果你想要一个“AND”条件查询,试试这个:

    Comment.
      where(:created_at => time_range).
      where("user_id is not in (?)",[user_ids])
    

    这将产生类似的 SQL:select ... where ... AND ...

    如果你想让WHERE子句更复杂,比如:where ( a AND b) OR (c AND d),你必须自己把条件组合到子句中,例如

    Comment.where("(a AND b ) OR (c AND d)")
    

    【讨论】:

    • ActiveRecord::StatementInvalid: PG::Error: ERROR: syntax error at or near "in" 出现错误
    【解决方案2】:
    User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
    

    这样就好了。

    【讨论】:

      【解决方案3】:
      User.where(name: 'Joe', email: 'joe@example.com')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-16
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 2021-05-13
        • 2011-02-13
        相关资源
        最近更新 更多