首页 > 解决方案 > nodejs mysql查询依赖于另一个查询结果,然后在循环中将第二个查询结果插入到第一个

问题描述

我需要运行第一个查询,从中获得拍卖列表,我需要运行第二个查询,对于每次拍卖,我都会获得此拍卖的最低出价。在我得到结果后,我需要将最低出价推送到我从 for 循环中的第一个查询(results1)收到的拍卖 json。当我控制台日志结果时,我得到一个包含 9 个对象(应该是 3 个)的数组,并且最低出价属性仅存在于其中 3 个对象上,这可能是更好的方法。添加最低出价后的结果的console.log: https ://imgur.com/a/eiYcycZ

router.get('/get-live-auctions', auth, (req, res) => {
  try {

    const userID = req.userData.userID;
    db.query(`SELECT auctions.UID,auctions.OriginCompany,auctions.DestinationCompany,auctions.OriginAddress,auctions.DestinationAddress,auctions.PickupDate,auctions.TotalWeight,auctions.StartDate,auctions.BidEndDate,auctions.AuctionEndDate,auctions.AuctionState,auctions.AuctionSerialNumber
    From auctions
    WHERE UserId='${userID}' AND AuctionState = 2 OR AuctionState = 3 OR AuctionState = 4`, (
      err, results, fields) => {
        for (let i = 0; i < results.length; i++) {
          let auctionsIDS = results[i].UID;
          db.query(`SELECT MIN(TotalPrice) AS lowestBid
          FROM bids
          Where AuctionID = '${auctionsIDS}'
          `, (err2, results2, fields2) => {
              let lowestBid = results2[0].lowestBid;
              results.lowestBid = lowestBid;
              console.log(results);
              if (err2) return res.send(error);
            }
          )
        }
        res.status(200).json(results);
      });

  } catch (error) {
    return res.status(500).send("Server error");
  }
})

如何解决这个问题?

标签: mysqlnode.js

解决方案


推荐阅读