【问题标题】:Rails Query nil problemsRails 查询零问题
【发布时间】:2016-02-15 17:18:05
【问题描述】:

我正在尝试获取所有过期日期(日期类型)为 nil 的优惠券:

  @coupons = @deal.coupons.all 
  @coupons = @coupons.where("expirationDate = ?", nil)

但由于某种原因,上面的代码不起作用。 但是,如果我这样做:

@coupons = @deal.coupons.all
@coupons = @coupons.where(expirationDate: nil)

它会得到我想要的所有 nil 优惠券。我很困惑为什么第一个不起作用,但第二个起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    例如。

    User.where("name = ?",nil)
    

    sql 输出:

    SELECT "users".* FROM "users"  WHERE (name = NULL)
    

    另一种格式:

    u = User.where(name: nil)
    

    sql输出:

    SELECT "users".* FROM "users"  WHERE "users"."name" IS NULL
    

    你会发现 sql 不同。 SQL is null and = null [duplicate]的详细信息

    【讨论】:

      【解决方案2】:

      NULLNOT NULL的SQL查询如下:

      expirationDate IS NULLexpirationDate IS NOT NULL

      它不适用于等号“=”符号。你不能在 SQL 中做 expirationDate = NULL

      你也可以这样试试

      @coupons = @coupons.where("expirationDate IS NULL")
      

      您可以查看此答案,了解在https://stackoverflow.com/a/4252615/343679 条件下使用null 的其他替代方法

      【讨论】:

        猜你喜欢
        • 2011-08-24
        • 2015-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-03
        • 2011-09-25
        • 2019-05-13
        相关资源
        最近更新 更多