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

后端 未结 7 607
梦毁少年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:11

    It looks like you may have been close based on your comment to @ebohlman's answer. You can use WHERE id = ANY($1::int[]). PostgreSQL will convert the array to the type the parameter is cast to in $1::int[]. So here's a contrived example that works for me:

    var ids = [1,3,4]; 
    
    var q = client.query('SELECT Id FROM MyTable WHERE Id = ANY($1::int[])',[ids]);
    
    q.on('row', function(row) {
      console.log(row);
    })
    
    // outputs: { id: 1 }
    //          { id: 3 }
    //          { id: 4 }
    

提交回复
热议问题