首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript在值列表中的“MySQL”

Javascript在值列表中的“MySQL”
EN

Stack Overflow用户
提问于 2017-04-02 08:00:53
回答 6查看 6.2K关注 0票数 4

我有一个数组,其中每个元素对应于一个字母数字字符串,让我们说:

userIds :Ab526,shvx23 23,23636dsd

我希望将它转换成这样的格式,这样我就可以将这个字符串列表传递给mySQL query的mySQL IN子句,如下所示:

从“(.)”中userIds所在的用户中选择*;

我尝试使用array.join()和许多其他方法,这些方法都是在某个地方提出的,但都是徒劳的。

代码语言:javascript
运行
复制
var userIds = ['Ab526', 'shvx23', '23636dsd']
var ids    = userIds.join(',');
var query  = 'Select * from Users where userIds in (' + ids + ')'; 
console.log(query);

其结果是:

从userIds所在的用户中选择* ('Ab526,shvx23,23636dsd');

如果有人能提出一个解决方案,作为我如何能够实现我想要的,这将是非常有帮助的。

EN

回答 6

Stack Overflow用户

发布于 2017-04-02 08:04:00

您可以映射引文值并在稍后加入。

代码语言:javascript
运行
复制
var userIds = ['Ab526', 'shvx23', '2363\'6dsd'],
    result = userIds.map(function (a) { return "'" + a.replace("'", "''") + "'"; }).join();
    
console.log(result);

票数 2
EN

Stack Overflow用户

发布于 2017-04-02 08:20:24

您可以在数组上使用减缩:

代码语言:javascript
运行
复制
var userIds = ['Ab526', 'shvx23', '23636dsd'];
    var clause = userIds.reduce(
                 function (cl , a, currIndex, arr) 
                     { 
                     return cl + 
                      (currIndex == 0 ? "" : ",")  
                     +"'"+ a + "'"+ 
                     (currIndex == arr.length-1 ? ")" : "") ; } , "(" );
    
    console.log(clause );

票数 2
EN

Stack Overflow用户

发布于 2017-04-02 08:21:44

您可以使用以下代码:

代码语言:javascript
运行
复制
var userIds = ['Ab526', 'shvx23', '23636dsd'];
var ids = '';
userIds.forEach(function(entry,index) {
    ids += (index == 0) ? entry : ',' + entry;
});
console.log(ids);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43166013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档