Home > Software design >  How do I map one query to another in node.js and mysql
How do I map one query to another in node.js and mysql

Time:07-27

I know that you can wrap on query in another but is it possible to map them? I was wondering if there’s some way to make a query that returns a list and then run another query with the id from each of the items from the first. I’d imagine it like: app.get(“/sentences”, (req, res) {db.query(‘SELECT sentence_id From sentences’).map(id => db.query(‘SELECT * FROM paragraphs WHERE sentence_id = ?’, id,(err, result) => { if (err){console.log(err);} else {res.send(result);}});})

I know that this code looks terrible but I hope that it gets the idea across.

CodePudding user response:

First, use code blocks.

Second, you're looking for subqueries https://www.mysqltutorial.org/mysql-subquery/

As in the example:

SELECT 
    lastName, firstName
FROM
    employees
WHERE
    officeCode IN (SELECT 
            officeCode
        FROM
            offices
        WHERE
            country = 'USA');

The equivalent for you appears to be:

SELECT 
    *
FROM
    paragraphs
WHERE
    sentence_id IN (SELECT 
            sentence_id
        FROM
            sentences);
  • Related