简体   繁体   English

如何将列表作为参数传递给 postgres

[英]how to pass a list into postgres as a parameter

I am trying to run this with typeorm我正在尝试使用 typeorm 运行它

const fields = await queryRunner.query(
  `SELECT "fieldId", "name" FROM "field" WHERE "name" IN ($1) `,
  [...fieldNames]
);

where fieldNames is a list.其中 fieldNames 是一个列表。 But I get an error saying bind message supplies 5 parameters但是我收到一条错误bind message supplies 5 parametersbind message supplies 5 parameters

Is there anyway to make this dynamic so i can pass a list and get returned values?有没有办法让这个动态化,这样我就可以传递一个列表并获得返回值? This isn't unique to type orm -- it's an issue with postgres这不是 orm 类型独有的——这是 postgres 的问题

Each element of an IN query is a separate parameter. IN查询的每个元素都是一个单独的参数。 If you want to pass five elements you need five parameters.如果要传递五个元素,则需要五个参数。

SELECT "fieldId", "name"
FROM "field"
WHERE "name" IN ($1,$2,$3,$4,$5)

This means dynamically generating the SQL to match the number of values you have.这意味着动态生成 SQL 以匹配您拥有的值的数量。


Postgres offers a better way. Postgres 提供了更好的方法。 Use the any operator .使用any运算符 This works with an array which is a single value.这适用于一个单一值的数组。

SELECT "fieldId", "name"
FROM "field"
WHERE "name" = ANY($1)

Now you should be able to pass an array of values as your first parameter .现在您应该能够将一组值作为您的第一个参数传递。 Typeorm should convert it to a Postgres Array . Typeorm 应该将其转换为Postgres Array

const sql = `
  select fieldId, name
  from field
  where name = ANY($1)
`
const values = [['manny','moe','jack']]
client.query(sql, values)

This should result in:这应该导致:

  select fieldId, name
  from field
  where name = ANY(ARRAY['manny','moe','jack'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM