Multi-table query Node + Mysql

2

Considering the need to bring the result of a second table, based on the result of the first one, how would you do it with NodeJS? In PHP I would bring the result, and within while I would make another query by passing the ID of the first query (I know it is not the best practice).

// List users

router.get("/users", (req, res) => {
    let query = "SELECT * FROM ??";
    let table = ["users"];
    query = mysql.format(query, table);
    connection.query(query, (err, rows) => {
        if(err){
            res.json({"Error": true, "Message": "Erro ao executar query do Mysql"});
        }else{
            res.json({"Error": false, "Message": "Successo", "Users": rows});
        }
    });
});

Listing User Information

let query = "SELECT * FROM ?? WHERE ?? = ?";
let table = ["users_info"];
query = mysql.format(query, table);

It would be in the case of these two, list the user and list his information that is in another table.

    
asked by anonymous 29.08.2017 / 02:57

1 answer

2

You can do this in a single select where the two tables together. If I understood sexo , nascimento , descricao are from the users_info table, then a select set would look like this:

SELECT ui.sexo, ui.nascimento, ui.descricao, u.id 
FROM users AS u
LEFT JOIN users_info AS ui ON u.id = ui.id_user
WHERE u.id=??

And the columns that this select gives will be sexo , nascimento , descricao are of the users_info table, and id of the users table.     

29.08.2017 / 15:32