Query in multiple Node + Mysql tables

Asked

Viewed 402 times

2

Taking into account the need to bring the result of a second table, based on the result of the first, how would you do this with Nodejs ? In PHP I would bring the result, and inside a while did another query by passing the ID of the first query (I know that 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});
        }
    });
});

List information from the user

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 in another table.

  • You can show the two SELECT you want to do?

  • @Sergio Editei o post

  • Ok, and the query is only for 1 user at a time right?

  • What is the column of users which is reference to users_info and what’s the column? You can do it with a LEFT JOIN.

  • @Sergio Yes, one user at a time, the columns would be sexo, nascimento, descricao, in this table, I have a column that has the id_user

1 answer

2


You can do this in a single select where you join the two tables. If I understand correctly sexo, nascimento, descricao table users_info, then a select set would be 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 table users_info, and id table users.

  • I’ll test and give you a feedback

  • Sergio, take my mind off it, with Node I’m forced to work the way I’m working up, or can I work the way you did? instead of putting ??in everything, I can just go right through?

  • @Rafaelaugusto use ?? is for this library to escape and prevent SQL injections. But you can use it like this: connection.query(query, [dados],
 (err, rows) without needing mysql.format. Or using template strings and the .escape() of that library.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.