node mysql 查询_node-mysql 如何多次查询

易炳
2023-12-01

例如,mysql里有两个表:

tb_user: userId, userName

tb_userBook: userId, bookId, bookName

想通过检索最终得到这样的结果:

[

{

"userId": 1,

"userName": "张三",

"userBook": [

{

"bookId": 1,

"bookname": "书名1"

},

{

"bookId": 2,

"bookname": "书名2"

}

...

]

},

{

"userId": 2,

"userName": "李四",

"userBook": [

{

"bookId": 3,

"bookname": "书名3"

}

]

}

...

]

如果是使用php的话,可以直接先获得所有tb_user的数据,然后遍历根据userId去搜索tb_userBook:

$info = array();

$userResult = mysql_query("SELECT * FROM tb_user");

if ($userResult) {

while ($user = mysql_fetch_assoc($userResult)) {

$bookInfo = array();

$bookResult = mysql_query("SELECT * FROM tb_userBook WHERE userId={$user['userId']}");

if ($bookResult) {

while ($book = mysql_fetch_assoc($bookResult)) {

array_push($bookInfo, $book);

}

}

array_push($info, $bookInfo);

}

}

echo json_encode($info);

//

但是node-mysql里面是异步回调,怎么在第一次检索完tb_user后循环获取相应的tb_userBook信息呢?

我尝试使用async模块来保持嵌套的次数,但碰到那个循环还是没办法下手....

 类似资料: