英文:
postgreSQL query only users that their id is in the array
问题
我正在使用postgreSQL作为我的node.js应用程序的数据库,我得到了一个ID数组,例如["1","2","3"],我想查询只包含在此数组中的用户的信息。
代码如下:
if (ids){
users = await pool.query(`SELECT * FROM users WHERE id IN ($1:csv)`, [members])
}
我在node.js中使用了pool.query,但是这里显示的命令不起作用,所以我不确定该如何做,请谢谢任何帮助。
英文:
I'm using postgreSQL as my database for node.js app, I'm given an array of id's for example ["1","2","3"], and I want to query only users that their id is include in this array
so it going like this
if (ids){
users = await pool.query(`SELECT * FROM users WHERE id IN ($1:csv)`, [members])
}
I'm using pool.query on nodejs, but this command shown here is not working so I don't exactly knows how to do that, thanks for any help
答案1
得分: 2
这在你使用 node-postgres npm 模块进行数据查询时有效。
所以在创建了一个连接池之后,使用以下查询结构:
const query = `
SELECT *
FROM abc
WHERE id IN (${ids.map((_, i) => `$${i + 1}`).join(',')} );
`;
然后运行 pool.query
命令,将查询作为参数传递。
然而请注意,此查询使用了数组映射,这种方法可能会有一些开销。
postgresSQL
英文:
This works if you are using the node-postgres npm module for data queries.
So after creating a Pool, use the following query structure:
const query = "
SELECT *
FROM abc
WHERE id IN (${ids.map((_, i) => `$${i + 1}`).join(',')});
";
and then run the pool.query command passing the query as the parameter.
However please note that the query uses array mapping, and this approach can be a bit expensive.
#postgresSQL
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论