如何在可选参数上查询postgres?

jha*_*amm 9 postgresql

我正在设置REST服务,我正在使用它postgres作为数据存储.我想知道如何设置postgres查询以使用可选参数.即:

SELECT * from users 
where hair_color = $1 
and eye_color = $2
Run Code Online (Sandbox Code Playgroud)

$ 1和$ 2来自请求:[req.body.hair_color,req.body.eye_color]

如果用户没有通过该怎么办?eye_color在这种情况下,我想要所有的眼睛颜色.我假设我不必if/else在这里做一堆陈述.创建此查询的简洁方法是什么?

Dav*_*esh 16

在这里,我做了两个hair_coloreye_color可选的.(通过你的语言相当于NULL).

SELECT * from users where 
  ($1 is null or hair_color = $1) and 
  ($2 is null or eye_color = $2);
Run Code Online (Sandbox Code Playgroud)

  • 是的,在 PostgreSQL 中,这实际上往往会得到很好的优化 - Pg 会注意到 `NULL IS NULL` 总是 true,所以它不需要评估 `hair_color = NULL`。所以它将删除整个条款。不过,在使用准备好的语句时,您需要使用相当新的 PostgreSQL 版本(我认为是 9.1)才能正常工作。 (2认同)