首页 > 解决方案 > 带有条件参数的 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])

标签: postgresqlnode-postgres

解决方案


你可以使用

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

但总的来说,这是查询构建器库是合适解决方案的地方。


推荐阅读