带有条件参数的Node-postgres准备语句

时间:2020-07-16 12:47:18

标签: postgresql node-postgres

有没有一种方法可以查询一些您可能无法定义(不需要)的条件

const c = {
  id?: number
  type?: string
}

const sql = `SELECT * FROM smth WHERE id=$1 AND type=$2`

query(sql , [c.id, c.type])

1 个答案:

答案 0 :(得分:2)

您可以使用

const sql = `SELECT * FROM smth WHERE ($1::int IS NULL OR id=$1) AND ($2::text IS NULL OR type=$2)`;

但是通常在这里,查询构建器库是合适的解决方案。

相关问题