2014-10-31 28 views
-3

我需要SQL查詢到MySQL另一個函數內部到MySQL同步請求,並收到我的主函數返回後查詢的結果值作出的node.js

connectionPool.getConnection(function (err, connection) { 
     connection.query("SELECT * FROM `sys_menu_top` WHERE `Type` = 'top' AND Active = 1 ORDER BY `Order`", function (err, rows, fields) { 
     if (rows) { 

      async.each(rows, function (row, callback) { 
      row.children = []; 
      connectionPool.getConnection(function (err, connection, sql) { 
       connection.query("SELECT * FROM `sys_menu_top` WHERE Parent = " + row.ID, function (err, children, fields) { 
//        console.log(children); 
       if (!err && children.length > 0) { 
        children.forEach(function (child) { 
        row.children.push(child); 
        }); 
        row.children.push(children); 
       } 
       else { 
        console.log(err); 
       } 
       }); 
      }); 
      callback(); 
      }, function (err) { 
      if (err) 
       console.error('error looping array\n\n'); 
      }); 
      process.nextTick(function() { 
      cb(null, rows); 
      });   
     } 

     }); 

    }); 

我的代碼返回行沒有孩子,但我可以在函數返回第一個查詢結果後在控制檯中接收子項。我需要把每行的孩子放到這一行然後返回結果。

+0

你爲什麼不使用加入這個? – 2014-10-31 09:43:03

+0

我沒有這個表上的索引,我不能修改數據庫結構。所以,如果我將有1千兆字節的8千行的表,這將是一個問題。我會用if語句擴展這段代碼,所以在某些情況下我不需要再進行第二次查詢(在沒有索引的情況下在1Gb表上進行不必要的連接並不是一個好主意)。這個問題不是關於MYSQL,而是關於node.js – 2014-10-31 10:30:37

+0

你確實有一個索引...... WHERE Parent =「+ row.ID' – 2014-10-31 10:32:16

回答

0

我知道它有不同的方法,但它可能是值得一試什麼如下:

async.waterfall([ 
     function (callback) { 
     var q = "SELECT * FROM Rows"; 

     executeQuery(q, function(err, rows, fields) { 
      if (err) { callback(err); return; }; 
      if (rows) { 
       callback(null, rows); 
       return; 
      } 
     }); 
     }, 
     function (rows, callback) { 
     console.log(rows); 
     for (k in rows) { 
      if (rows[k].Parent != null) { 
       child = rows[k].id; 
       parent = rows[k].Parent; 

       for (j in rows) { 
        if (rows[j].id == parent) { 
         if (!rows[j].Children) rows[j].Children = []; 
         rows[j].Children.push(child); 
        } 
       } 
      } 
     } 
     callback(null, rows); 
     } 
    ], 
    function (err, rows) { 
      console.log(rows); 
}); 

我得到我的測試表:

[ { id: 1, Parent: null }, 
    { id: 2, Parent: 1 }, 
    { id: 3, Parent: 1 } ] 
[ { id: 1, Parent: null, Children: [ 2, 3 ] }, 
    { id: 2, Parent: 1 }, 
    { id: 3, Parent: 1 } ]