pg-promise 多个 OR in where 子句

pg-promise mulitple OR in where clause

我在使用 pg-promise 时遇到了一些问题。

我想在 WHERE 子句中指定未定义数量的参数。

所有参数将与 OR 连接。

db.any(
  'SELECT genre FROM genres'+
  'WHERE ( (genres.genre LIKE \'Animation\' OR genres.genre LIKE \'Action\') ')
  .then(function(data) {
    // success;
  })
  .catch(function(error) {
    // error;
  });
});

我没有一个一个地指定参数,而是有一个由用户传递的流派数组。

我想做这样的事情...

var genres = ["Action", "Adventure", "Romantic"];   
db.any(
      'SELECT genre FROM genres'+
      'WHERE ( (genres.genre LIKE ) '), [genres])
      .then(function(data) {
        // success;
      })
      .catch(function(error) {
        // error;
      });
});

我找不到让它工作的方法。

感谢您的帮助!

您的问题更多是关于 PostgreSQL 语法的多重 LIKE 用法,而不是 pg-promise. See Combining multiple like queries

最简单的方法是使用 LIKE ANY(array[...]) 语法:

const genres = ['Action', 'Adventure', 'Romantic'];

db.any('SELECT genre FROM genres WHERE genre LIKE ANY()'), [genres])
      .then(data => {
          // success, data = matching genres
      })
      .catch(error => {
          // error
      });
});

这将格式化并执行:

SELECT genre FROM genres WHERE genre LIKE ANY(array['Action', 'Adventure', 'Romantic'])