首页 > 解决方案 > 将硬编码查询从 MYSQL 迁移到 PostgreSQL

问题描述

嗨,我有一个看起来像这样的“mysql”查询:

... WHERE (maintenanceLockTimestamp + "+ delay+" SECOND) < CURRENT_TIMESTAMP ) ) "

问题是,我们需要从 MYSQL 转移到 PostgreSQL,但是在执行相同的查询时,我得到:

Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "SECONDS"

我在这里检查:https ://www.postgresqltutorial.com/postgresql-date-functions/

看起来 PostgreSQL 中不存在 SECOND 函数,你知道有什么替代方法吗?

谢谢

标签: mysqlsqlpostgresqlmigrationhardcoded

解决方案


在 Postgres 中,您可以使用:

where maintenanceLockTimestamp + :delay * interval '1 second' < current_timestamp

请注意使用参数来避免将查询字符串与文字值混淆。

在这两个数据库中,最好使用以下日期/时间算法编写current_timestamp

where maintenanceLockTimestamp < current_timestamp - ? second  -- MySQL
where maintenanceLockTimestamp < current_timestamp - :delay * interval '1 second'  -- Postgres

这允许优化器使用索引来maintenanceLockTimestamp提高性能。


推荐阅读