在参数数组中传递一个整数数组

Pass an array of integers in array of parameters

我正在尝试按照 pg-promise docs 中的建议在 pg-promise 的参数数组中传递一个参数数组。

db.any("SELECT fieldname FROM table WHERE fieldname =  AND fieldname2 IN ()",
        [1,[[1730442],[1695256]],[487413],[454336]]])
    .then(function (data) {
        console.log("DATA:", data); // print data;
    })
    .catch(); 

但它不起作用,我返回了 "missing ) after argument list" 错误。 或者 "operator does not exist: integer = integer[]]" 错误,如果我将参数替换为 :

[1,[1730442]]

当然,如果我这样通过它,它就有效了:

[1,1730442]

当涉及到其他参数时,这是传递值数组的正确方法吗?

我也尝试删除 $2 周围的括号,但没有成功。

我是 pg-promise 的作者。


你的例子有些混乱...

您在查询中只使用了两个变量,但传入了四个值:

  • 1
  • [[1730442],[1695256]]
  • [487413]
  • [454336]

而且你的语法没有有效的 JavaScript,因为你最后使用的 ] 没有匹配的开头,所以很难理解你到底是什么试图通过。

然后为什么要再次将所有值包装在数组中?我相信这只是 IN() 语句中您想要的整数列表。

当您想在 WHERE IN() 中使用值时,它实际上并不是您要传入的那些值的数组,它是一个以逗号分隔的值列表。

如果您将示例更改为以下内容:

db.any('SELECT fieldname FROM table WHERE fieldname =  AND fieldname2 IN (:csv)',
[1, [1730442,1695256,487413,454336]])

您将获得正确的注入值列表。

另请参阅:

另一种可能是:

db.any("SELECT fieldname FROM table WHERE fieldname =  AND fieldname2 = any ()",
        [1,[1730442,1695256,487413,454336]])
    .then(function (data) {
        console.log("DATA:", data); // print data;
    })
    .catch(); 

来自 postgresql 手册:https://www.postgresql.org/docs/9.5/static/functions-comparisons.html

The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ANY is "true" if any true result is obtained. The result is "false" if no true result is found (including the case where the array has zero elements).

If the array expression yields a null array, the result of ANY will be null. If the left-hand expression yields null, the result of ANY is ordinarily null (though a non-strict comparison operator could possibly yield a different result). Also, if the right-hand array contains any null elements and no true comparison result is obtained, the result of ANY will be null, not false (again, assuming a strict comparison operator). This is in accordance with SQL's normal rules for Boolean combinations of null values.

SOME is a synonym for ANY.