📜  日期范围查询 knex - Javascript (1)

📅  最后修改于: 2023-12-03 14:55:09.171000             🧑  作者: Mango

Knex - Javascript 中的日期范围查询

Knex.js 是一个强大、灵活的 Node.js SQL 查询构建器,支持 Postgres、MySQL、MySQL2 和 SQLite3 数据库。在 Knex 中进行日期范围查询是一项常见的任务,可以使用以下方法来处理。

查询日期范围

如果您想查询一个日期范围内的数据,可以使用 whereBetween 方法。以下是一个示例,查询创建时间在 2021 年 1 月 1 日至 2021 年 6 月 30 日之间的所有记录。

const startDate = new Date("2021-01-01");
const endDate = new Date("2021-06-30");

knex('tableName')
  .whereBetween('create_date', [startDate, endDate])
  .then((results) => {
    console.log(results);
  })
  .catch((error) => {
    console.error(error);
  });
查询特定日期

如果您想查询某个特定日期的数据,可以使用 where 方法。以下是一个示例,查询创建时间在 2021 年 1 月 1 日的记录。

const targetDate = new Date("2021-01-01");

knex('tableName')
  .where('create_date', targetDate)
  .then((results) => {
    console.log(results);
  })
  .catch((error) => {
    console.error(error);
  });
查询最近日期

如果您想查询最近几天或最近几个月的数据,可以结合使用 JavaScript 中的 Date 对象和 Knex 的 where 方法。以下是一个示例,查询创建时间在过去 7 天内的记录。

const targetDate = new Date();
const daysAgo = 7;
targetDate.setDate(targetDate.getDate() - daysAgo);

knex('tableName')
  .where('create_date', '>=', targetDate)
  .then((results) => {
    console.log(results);
  })
  .catch((error) => {
    console.error(error);
  });
结论

以上就是在 Knex.js 中进行日期范围查询的常见方法。无论您想要查询特定日期还是日期范围内的数据,Knex 都提供了各种方法来帮助您完成任务。如果您需要更多关于 Knex 的帮助,请参阅 Knex.js 官方文档。