简体   繁体   中英

Node.js MySQL query execution flow

If I have a MySQL query that returns a value that will be used again in a WHERE clause, will this work with Node.js' asynchronous execution flow?

Generally this might be the case:

SELECT
customerId FROM Customers
WHERE customerName=nikolas

Then the result would be stored like so:

var customerId = customerId

And reused in another query:

SELECT
orderId FROM Orders
WHERE customerId=customerId

Will this fetch me the orderId of the customer Nikolas that was returned in the first query?

Will written queries run sequentially?

It really depends on the module you're using. One of the most commonly used drivers, node-mysql , is asynchronous, so the code won't run sequentially. Instead, you'd have to use callbacks:

var query1 = 'SELECT customerId FROM Customers WHERE customerName = nikolas';
var query2 = 'SELECT orderId FROM Orders WHERE customerId = ';

connection.connect();
connection.query(query1, function(err, rows, fields) {
  var customerId = rows[0].customerId;
  connection.query(query2 + customerId, function(err, rows, fields) {
    connection.end();
    // results are here
  });
});

In Node.js, you usually want to write asynchronous code. There probably is a synchronous MySQL driver module somewhere, but most don't have a case where they would want to block their process with a synchronous database call.

In the code written by @hexacyanide. The second query won't run until the first query has run, because the code is waiting for the response of the first query. So that answers your doubt of sequentially. And also you don't need to use two queries for this. You can simply join the two tables and get the result in a single query. Something like this:

SELECT orders.orderId 
       FROM Orders orders 
       JOIN Customers customers 
       ON orders.customerId = customers.customerId
       WHERE customers.customerName='Nikolas'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM