Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何强制2个MySQL查询串联运行_Mysql_Node.js - Fatal编程技术网

如何强制2个MySQL查询串联运行

如何强制2个MySQL查询串联运行,mysql,node.js,Mysql,Node.js,我需要每天获取所有逾期客户的列表,并将其插入到新表中,然后我需要将日期移动一个月,以便下个月再次处理 目前我正在运行2个SQL查询 insert into history select * from customers where nextdate<CURDATE() update customers set nextdate=calculation() where nextdate<CURDATE() 但有时会更新客户,但不会将其插入历史记录 在我看来,更新在mysql完成选择之

我需要每天获取所有逾期客户的列表,并将其插入到新表中,然后我需要将日期移动一个月,以便下个月再次处理

目前我正在运行2个SQL查询

insert into history select * from customers where nextdate<CURDATE()
update customers set nextdate=calculation() where nextdate<CURDATE()
但有时会更新客户,但不会将其插入历史记录

在我看来,更新在mysql完成选择之前就开始运行了

我使用的是Node js,我目前用于序列化的方法是,我在insert的回调中运行更新,但insert可能在代码实际运行之前被回调


这并不是每次都会发生,但我认为制作一个同时包含这两者的存储过程会有所帮助,有人有过这方面的经验吗

这里有两个问题。首先,SELECT和UPDATE不会等待每一次,因为SELECT不会锁定表。您可以使用以下命令强制锁定读取:


在历史记录中插入SELECT*FROM customers,其中nextdate可以使用nodejs提供的承诺使其串联,也可以使用异步串联

异步系列 或者你可以选择第一种

使用承诺 我建议你用这个

var conn = db.config(mysql);

run_query(conn,[ 'insert into history select * from customers where nextdate<CURDATE()' ]).then(function(result){

 console.log(result); // result of 1st query

 return run_query(conn,[ 'update customers set nextdate=calculation() where nextdate<CURDATE()']);

}).then(function(result){

   console.log(result.something); // result of 2nd query 
    conn.end();
}).catch(function(err){
  // will run if any error occur
   console.log('there was an error', err);

});

这里两者都执行,但插入不等待更新,事务是否确保序列化?插入和更新都是锁定操作,因此在插入完成之前更新不能启动。这就是说,由于您的INSERT依赖于SELECT,因此完全有可能您的SELECT实际上没有获得所需的数据,这是值得研究的。INSERT与update不在同一个表上,它们是否锁定了整个DB?SELECT和update使用完全相同的where子句,因此,除非记录正在更改,否则它们必须具有相同的行。然后,您可能希望显式锁定表,以便在更新之前始终运行select,即读取和从不锁定表。您可以将此设置为锁定读取,我已经为您更新了答案,并提供了有关如何执行此操作的说明。显示一些最小的、可运行的代码来演示此问题?这肯定比仅要求DB引擎使其选择锁定操作并在事务中包装调用要慢。
var conn = db.config(mysql);

run_query(conn,[ 'insert into history select * from customers where nextdate<CURDATE()' ]).then(function(result){

 console.log(result); // result of 1st query

 return run_query(conn,[ 'update customers set nextdate=calculation() where nextdate<CURDATE()']);

}).then(function(result){

   console.log(result.something); // result of 2nd query 
    conn.end();
}).catch(function(err){
  // will run if any error occur
   console.log('there was an error', err);

});