简体   繁体   English

Node.js MySQL查询执行流程

[英]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? 如果我有一个MySQL查询,该查询返回的值将在WHERE子句中再次使用,那么它将与Node.js的异步执行流程一起使用吗?

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? 这会获取我在第一个查询中返回的客户NikolasorderId吗?

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. 最常用的驱动程序之一node-mysql是异步的,因此代码不会顺序运行。 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. 在Node.js中,您通常要编写异步代码。 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. 某个地方可能有一个同步的MySQL驱动程序模块,但是大多数情况下,他们都不希望通过同步数据库调用来阻塞其进程。

In the code written by @hexacyanide. 在@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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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