使用带有 IN 子句的 node-postgres select 的正确方法

Art*_*urJ 0 postgresql node.js express node-postgres

我正在尝试如何使用node-postgres将逗号分隔的值字符串传递到子句查询中的postgres select中,但不幸的是似乎无法让它工作并且找不到任何示例。

我有以下代码:

function getUser() {
  let inList = "'qwerty', 'qaz'";

  const result = await pgPool.query("SELECT name FROM my_table WHERE info IN ($1)", [inList]);  
  if (result.rowCount == 1) return result.rows.map(row => row.name)
  return false
}
Run Code Online (Sandbox Code Playgroud)

基本上希望处理最终结果查询:

SELECT name FROM my_table WHERE info IN ('qwerty', 'qaz')

不确定这是否真的是使用 pgPool 执行此操作的正确方法?

小智 5

正确的方法是 Github 上的常见问题解答 --> https://github.com/brianc/node-postgres/wiki/FAQ#11-how-do-i-build-a-where-foo-in--query -查找与值数组匹配的行

你应该能够这样做:

 pgPool.query("SELECT name FROM my_table WHERE info = ANY ($1)", [jsArray], ...);
Run Code Online (Sandbox Code Playgroud)