简体   繁体   中英

How store queries Mysql

I'm going to fetch my database twice with different values ​​for Id. But I need to save those two queries somewhere and then send them to the res.render. I already tried to save in array but it returns undefined.

app.post('/searchInventory', urlencodedParser, function(req, res){
        con.query("SELECT id FROM products WHERE name LIKE '%" + req.body.keyword + "%'", function(err, result){
            data = [];
            for(var a = 0; a < result.length; a++){
                console.log(a);
                con.query("SELECT products.id AS id, products.name AS name, products.price AS price, SUM(enter.quantity) AS quantity FROM products JOIN enter ON products.id = enter.id_prod WHERE enter.id_prod = "+mysql.escape(result[a].id)+";", function(err, results, fields){
                // I need to store the query from here
                data =+ results
                });
            }
            console.log(data); //Undefined
            res.render('inventory', {results: results});
        });
    })

The question is around async db query which needs to be taken care. What first you can do to make it easy and readable is creating a query promise.

function dbQueryPromise(query) {
  return new Promise((resolve, reject) => {
    con.query(query, (err, results) => {
      if(err) return reject(err);
      resolve(results);
    })
  })
}

Now you can use this promise to handle your required behaviour :

dbQueryPromise("SELECT id FROM products WHERE name LIKE '%" + req.body.keyword + "%'")
  .then(results => {
   const promiseArray = results.map(result => {
     return dbQueryPromise("SELECT products.id AS id, products.name AS name, products.price AS price, SUM(enter.quantity) AS quantity FROM products JOIN enter ON products.id = enter.id_prod WHERE enter.id_prod = "+mysql.escape(result.id)+";")
   })
   Promise.all(promiseArray).then(allResults => { res.render('inventory', { results: allResults})})
})

You can use sub-query to query the product instead of query twice.

con.query("SELECT products.id AS id, products.name AS name, products.price AS price, SUM(enter.quantity) AS quantity FROM products JOIN enter ON products.id = enter.id_prod WHERE enter.id_prod IN ( SELECT id FROM products WHERE name LIKE '%?%') ", req.body.keyword, function( error, result){
    console.log(result)
})

also, data += result would not stack the array. You can use Array.prototype.concat to combine two array.

Example:

data = data.concat(result) 

or

data = [].concat(data, result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM