Home > Net >  Running Two Quaries on the same table and implement them on the same route
Running Two Quaries on the same table and implement them on the same route

Time:10-09

How can I make this work? I think I should use promises but I don't have much knowledge about them. I've read about them but couldn't create the structure as it's supposed to.

I simply wanna run two different queries on the same table and use the returning values on the same ejs file

    app.get('/', (req, res) => {

        db.query('SELECT COUNT(*) AS count, FORMAT(SUM(donation_amount),2) AS total FROM donations;', (err, result) => {
            if (err) throw err;
            let count = result[0].count; //since query column is requested as "count". we can use "count" to get back the raw value
            let total = result[0].total;
            res.render('home', { count: count, total: total }); // just the file name is enough. ejs engine looks up the file name in the "views" folder
        });

        db.query('SELECT CONCAT(first_name, ", ", last_name AS latest_donator, donation_amount AS amount FROM donations ORDER BY donation_time LIMIT 1;', (err, result) => {
            if (err) throw err;
            let donatorName = result[0].latest_donator;
            let amount = result[0].amount;
            res.render('home', {first_name: donatorName, amount: amount});
        });
     });

CodePudding user response:

You can only send the response (res.render(...)) once you have the result of both queries. Therefore you may want to do them sequentially like this.

app.get('/', (req, res) => {
    db.query('SELECT COUNT(*) AS count, FORMAT(SUM(donation_amount),2) AS total FROM donations;', (err, result) => {
        if (err) throw err;
        let count = result[0].count; //since query column is requested as "count". we can use "count" to get back the raw value
        let total = result[0].total;
        db.query('SELECT CONCAT(first_name, ", ", last_name AS latest_donator, donation_amount AS amount FROM donations ORDER BY donation_time LIMIT 1;', (err, result) => {
            if (err) throw err;
            let donatorName = result[0].latest_donator;
            let amount = result[0].amount;
            res.render('home', { first_name: donatorName, amount: amount, count: count, total: total });
        });
    });
});

But the queries are independent from eachother so you could run them in parallel.

  • Related