javascript node js mysql 查询 where id = ARRAY?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33957252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:04:23  来源:igfitidea点击:

node js mysql query where id = ARRAY?

javascriptmysqlnode.js

提问by iam

I am working to fetch data of listed users and I have an array of users like

我正在努力获取列出用户的数据,并且我有一系列用户,例如

var result_user_id = [
  {
    "id": 19
  },
  {
    "id": 20
  }
];

and I tried something like

我试过类似的东西

connection.query( 
   "select * from `contents` where `user_is` IN "+ result_user_id, 
   function( err_user, result_user ) {

   }
);

but unable to fetch related data. how to do that in node js.

但无法获取相关数据。如何在节点 js 中做到这一点。

回答by Vishnu

var o =[
  {
    "id": 19
  },
  {
    "id": 20
  }
];
var arr = o.map( function(el) { return el.id; });
connection.query( "select * from `contents` where `user_is` IN "+ arr, function( err_user, result_user ) { });

回答by Kedem

If you wish to take advantage of safe escaping (?) you can do the following:

如果您想利用安全转义 (?),您可以执行以下操作:

 connection.query('SELECT FROM `contents` WHERE `user_is` IN (' + 
   Array(result_user_id.length + 1).join('?').split('').join(',') + ')', result_user_id.map(p => p.id), function(err, result_user){});

回答by Tyler Edman

I know this question is a little bit older, but I found it via googled and stumbled across the same problem. This is the easiest solution I found:

我知道这个问题有点老,但我通过谷歌搜索发现它并偶然发现了同样的问题。这是我找到的最简单的解决方案:

    var result_user_id = [
  {
    "id": 19
  },
  {
    "id": 20
  }
];

var result_array = [];

  for (var i = 0; i < result_user_id; i++) {
      result_array[i] = result_user_id[i].id;
    }

connection.query( "select * from contents where user_is IN (?)", [result_array], function( err_user, result_user ) { });

回答by Neman

You can't just take the variable result_user_idas is and put it into the sql. Try something like:

您不能只是按result_user_id原样获取变量并将其放入 sql 中。尝试类似:

for (var i=0, len=result_user_id.length; i<len; i++){
   userIds += result_user_id[i].id + ",";
}

and then user the userIds instead of result_user_id in the sql you're trying to execute.

然后在您尝试执行的 sql 中使用 userIds 而不是 result_user_id 。