node-postgres: how to execute “WHERE col IN ()” query?

后端 未结 7 560
梦毁少年i
梦毁少年i 2020-11-28 06:02

I\'m trying to execute a query like this:

SELECT * FROM table WHERE id IN (1,2,3,4)

The problem is that the list of ids I want to filter ag

相关标签:
7条回答
  • 2020-11-28 06:23

    Using pg-promise, this works well via the CSV Filter (comma-separated values):

    const values = [1, 2, 3, 4];
    
    db.any('SELECT * FROM table WHERE id IN ($1:csv)', [values])
        .then(data => {
            console.log(data);
        })
        .catch(error => {
            console.log(error);
        });
    

    And to address the concern about various data types, :csv modifier serializes the array into csv, while converting all values into their proper PostgreSQL format, according to their JavaScript type, even supporting the Custom Type Formatting.

    And if you have mixed-type values like this: const values = [1, 'two', null, true], you still will get the correctly escaped SQL:

    SELECT * FROM table WHERE id IN (1, 'two', null, true)
    

    UPDATE

    From v7.5.1, pg-promise started supporting :list as an interchangeable alias for the :csv filter:

    db.any('SELECT * FROM table WHERE id IN ($1:list)', [values])
    
    0 讨论(0)
提交回复
热议问题