如何在Mysql + Node JS中的另一个查询中使用查询的结果数组?

时间:2018-12-06 10:26:13

标签: mysql node.js

  

我想在第二个查询(sql2)中使用第一个查询(sql1)的结果。第一个查询(sql1)的结果进入.ejs页,但第二个查询(sql2)没有结果。

 var sql1 = 'SELECT * FROM `Rooms`';
    con.query(sql1,function(err,rows,fields){
    if(!err)
    {
        var count=rows.length;
        for(i=0;i<count;i++)
        {
            arr_room[i]=rows[i].room_name;
        }
    }
    else
    {
        console.log('error...');

    }
  });

    var sql2 = 'SELECT * FROM Lights WHERE room_name =? ' ;
    con.query(sql,arr_room[0],function(err,rows,fields){
          if(!err)
          {
              var count=rows.length;
              for(i=0;i<count;i++)
              {
                arr_icon[i]=rows[i].icon;

              }
          }
          else
          {
              console.log('error...');

          }

     res.render('lighting',{arr_icon,arr_room}); 
    });

2 个答案:

答案 0 :(得分:1)

您需要将sql2嵌套到sql1中,在nodejs中,所有内容都是异步的,这意味着您必须等待某些事情先完成。

第二个查询中有一个错字,您叫sql而不是sql2

var sql1 = 'SELECT * FROM `Rooms`';
con.query(sql1, function(err, rows, fields) {
  if (!err) {
    var count = rows.length;
    //for (i = 0; i < count; i++) {
    //  arr_room[i] = rows[i].room_name;
    //}

    if (count) {

      // simplified version instead of for
      var arr_room = rows.map(i => i.room_name); 

      // you can safely use it inline since data comes straight from the database
      // query will use `in` condition: room_name in ('roomX','roomY', 'roomZ')
      var sql2 = `SELECT * FROM Lights WHERE room_name in ('${arr_room.join("','")}') `; 
      con.query(sql2, function(err, rows, fields) {
        if (!err) {
          var count = rows.length;
          for (i = 0; i < count; i++) {
            arr_icon[i] = rows[i].icon;

          }
        } else {
          console.log('error...');

        }

        res.render('lighting', {
          arr_icon,
          arr_room
        });
      });

    } else {

      console.log('no records to pass for sql2');

    }

  } else {
    console.log('error...');

  }
});

答案 1 :(得分:0)

我知道这个问题已经有了答案,但是我想提供一个仅SQL的解决方案:使用子查询而不是执行两个单独的查询并在Node.js中对其结果进行操作。

SELECT c.contact_ID, C.Contact_name
FROM contacts AS c 
JOIN data_values AS dv 
  ON c.contact_id = dv.contact_id 
JOIN data_fields AS df 
  ON dv.field_id = df.field_id 
JOIN data_cats_options AS dco 
  ON dv.field_val = dco.val_id 
WHERE c.contact_name = "Sachin" 
  AND (dv.field_id = 153 AND dco.val_id = 224 
  OR dv.field_id = 154 AND dco.val_id = 227)
GROUP BY c.contact_ID, C.Contact_name
HAVING count(*) = 2