node-mysql 如何多次查询


例如,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 :


 <?php
$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 模块来保持嵌套的次数,但碰到那个循环还是没办法下手....

node.js node-mysql mysql

THdian 10 years, 11 months ago

我使用node-mysql模块是这样干的。
SELECT a.userId,a.userName,b.userBook,b.bookId from tb_user as a join tb_userBook as b on a.userId=b.userId;
然后把结果拼成自己想要的格式

rained answered 10 years, 11 months ago

Your Answer