iterate over a connection to mysql and execute a query

1

I find the following problem ..

I generate a connection to mysql through the following package , where I have two tables: 'rto' and 'vta ' And based on that build an INNER JOIN where I show what is required, now I need to execute that query through each record of my table rto.

the code is as follows:

//mysql
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'excel'
});

//test conection
connection.connect((err) => {
  if (err) throw err;
  console.log('Connected!\n');
});

//count of remitos
var numrtos;
var gcrtoqy = 'SELECT COUNT(*) FROM rto;';
connection.query(gcrtoqy, (err, cb) => {
  if(err) throw err;
  numrtos = cb[0];
  numrtos = Object.values(numrtos)[0]
  console.log('CANT Remitos:', numrtos);
});

//
setTimeout(function(){
  console.log('\nData:\n');
  for (let i = 1; i <= numrtos; i++) {
    var fullqy = 'SELECT r.fecha, r.importe, v.fecha, v.importe FROM vta v INNER JOIN rto r ON r.id = '+i+' WHERE v.fecha >= r.fecha AND v.importe = r.importe LIMIT 1;';
    connection.query(fullqy, (err,match) => {
      if(err) throw err;
      console.log(match);
    });
  }
}, 500);

What I get is

Connected!

CANT Remitos: 3
CANT Ventas: 5

Data:

[ RowDataPacket { fecha: 2016-01-01T03:00:00.000Z, importe: 99 } ]
[ RowDataPacket { fecha: 2016-01-01T03:00:00.000Z, importe: 99 } ]
[ RowDataPacket { fecha: 2016-01-01T03:00:00.000Z, importe: 99 } ]

Although the number of requests is well done, it only shows me the result of the last one, since 'i' always has a value of 3.

The question would be, How do I assemble the loop asynchronously so that each query that goes through the loop runs independently?

P.D: I do not need to apply performance in the code. It is only to generate a single report.

Another alternative that I find is to make an insert with the result of the query in mysql

The query is as follows:

DROP PROCEDURE IF EXISTS ROWPERROW;
DELIMITER ;;

CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM rto INTO n;
SET i=1;
WHILE i<=n DO 


 INSERT INTO rtoxvta (fecharto, importerto, fechavta, importevta)
  SELECT r.fecha, r.importe, v.fecha, v.importe
    FROM vta v 
    left outer join rto r 
    ON r.id = i
    WHERE v.fecha >= r.fecha AND v.importe = r.importe 
    LIMIT 1;
  SET i = i + 1;
END WHILE;
End;
;;

CALL ROWPERROW();

but now the problem is the validation because I need to match the 'amount' field between two tables with an error margin of 2, and in mysql it is not possible. .or yes?

    
asked by Joaquin Diaz 13.06.2018 в 17:06
source

0 answers