【问题标题】:MySQL query fails in PostgreSQLMySQL 查询在 PostgreSQL 中失败
【发布时间】:2013-11-20 23:20:27
【问题描述】:

使用这个查询:

users = User.where('confirmed_at is NULL AND confirmation_sent_at <= DATE_SUB(NOW(), INTERVAL ? days)', 1)

在 mysql 中运行正常,但在 Postgresql 中失败:

PG::SyntaxError: ERROR:  syntax error at or near "1"
    LINE 1: ...AND confirmation_sent_at <= DATE_SUB(NOW(), INTERVAL 1 day))
                                                                 ^
    : SELECT "users".* FROM "users"
      WHERE (confirmed_at is NULL AND confirmation_sent_at <= DATE_SUB(NOW(), INTERVAL 1 day))

我试图理解但错过了这里的上下文。为什么这个查询中的整数 1 无效?

【问题讨论】:

    标签: mysql sql ruby-on-rails postgresql migrate


    【解决方案1】:

    PostgreSQL中没有DATE_SUB()函数,所以不能工作。

    这个表达式可以在 Postgres 中工作:

    ... AND confirmation_sent_at <= (now() - interval '1 day')
    

    或者,如果confirmation_sent_atdate

    ... AND confirmation_sent_at <= (now()::date - 1)
    

    【讨论】:

    • 谢谢,我完全错过了 DATE_SUB() 可能是一个 mysql 函数,只是比下面的那个更干净
    【解决方案2】:

    试试……

    users = User.where(
        "confirmed_at IS NULL " +
        "AND confirmation_sent_at <= (NOW() - INTERVAL '1 DAY')"
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 2015-11-28
      • 2016-06-21
      • 2014-11-01
      • 2019-09-27
      相关资源
      最近更新 更多