2017-04-16 53 views
0

我有一个名为UserRequests的表。我需要将RequestStatus更新为Completed,Time更新为当前日期时间以获得一对请求记录。我使用Node.js的mysql的模块https://github.com/mysqljs/mysqlNode.js MySQL在一个查询语句中更新多行

通常单个记录更新,我会做:

connection.query('update UserRequests set RequestStatus = ?, ReqCompletedDateTime = ? where idRequest = ?', ['Completed', new Date(), hReqId], function(err, rows){ 
    connection.release(); 
}); 

但在我来说,我需要完成,当前日期时间的状态更新多个UserRequests行。

我在列表中获取所有更新的请求标识。问题是我如何编写查询语句来将它们全部更新到一起。

我试过使用多个查询语句,但它没有工作。其他解决方案的几个也没有工作。很少有行吟诗人的解决方案我想:

connection.query('update UserRequests set RequestStatus = ?, ReqCompletedDateTime = ? where idRequest = ?', [['Completed', new Date(), 'somerowid1'], ['Completed', new Date(), 'somerowid2']], function(err, rows){ 
    connection.release(); 
}); 

OR

connection.query('update UserRequests set RequestStatus = ?, ReqCompletedDateTime = ? where idRequest = ?', [{'Completed', new Date(), 'somerowid1'}, {'Completed', new Date(), 'somerowid2'}], function(err, rows){ 
    connection.release(); 
}); 

我在做什么错?

回答

0

我不知道您可以将单独的参数列表传递给任何语言的查询。如果可以的话,它会对数据库产生多个查询。

您可以通过将所有值都放在in列表中。该查询将如下所示:

update UserRequests 
    set RequestStatus = ?, 
     ReqCompletedDateTime = now() 
    where idRequest in (?, ?); 

在代码:

connection.query('update UserRequests set RequestStatus = ?, ReqCompletedDateTime = now() where idRequest in (?, ?)', ['Completed', 'somerowid1', 'somerowid2'], function(err, rows) { 

不幸的是,你不能值列表参数的in。要么为每个值需要单独的占位符,要么需要将列表直接插入查询字符串(不推荐)。

另请注意,ReqCompletedDateTime使用数据库now()函数,而不是来自应用程序的日期/时间。这可确保列一致,并且不受其他机器上的时钟影响。

+0

我试过这段代码,但它只更新了'somerowid1'行,somerowid2行没有更新。 – codeinprogress

1

您正在寻找的 'IN' 操作符,所以你可以试试:

connection.query('update UserRequests set RequestStatus = ?, ReqCompletedDateTime = ? where idRequest IN (?)', ['Completed', new Date(), idsArray.join()], function(err, rows){ 
    connection.release(); 
}); 

特殊照顾 'idsArray' 应该是这样的:

​​

的 '加入' 功能将转换数组字符串

看看这个答案: update in

  • 请注意,我没有专门为您的情况测试此代码,但它应该可以工作!

祝你好运!

+0

我试过你的解决方案,虽然它不给我任何错误,但它也不更新行。 – codeinprogress

+0

你能发布你收到的回复吗? – Shachar

+0

在回调函数返回的“rows”var中显示:{“fieldCount”:0,“affectedRows”:0,“insertId”:0,“serverStatus”:2,“warningCount”:0,“message”:“ (行匹配:0改变:0警告:0“,”protocol41“:true,”changedRows“:0} – codeinprogress