使用 ARRAY 在 Postgres 上参数化 SQL

Parametrized SQL on Postgres with ARRAY

我是 运行 下面的 SQL 并且工作正常:

  const ids = book.map(({ id }) => id);
  const myQuery = `
    SELECT
      row_to_json(s)
    FROM (
      SELECT
        b.id, b.event_id, b.title, b.price, e.account_id
      FROM
        ticket_books b, event e
      WHERE
        b.event_id = e.id AND
        b.id = ANY(ARRAY[${ids}])
    ) s
  `;
  const result = await server.pg.query(myQuery);

我想切换到准备好的语句,所以我将上面的代码重写为:

  const myQuery = `
    SELECT
      row_to_json(s)
    FROM (
      SELECT
        b.id, b.event_id, b.title, b.price, e.account_id
      FROM
        ticket_books b, event e
      WHERE
        b.event_id = e.id AND
        b.id = ANY(ARRAY[])
    ) s
  `;
  const result = await server.pg.query(myQuery, [ids]);

准备好的语句版本失败:error: operator does not exist: integer = text

问题是什么?

pg 将为您制作数组。使用 b.id = ANY().