tkzlskg
tkzlskg

Reputation: 29

Selecting from 2 tables at one time in node js

I want to select all the patrols and select all the users from the database. But I got an error and I'm not sure why is it even an error.

The code that I wrote

connection.query("SELECT * FROM patrols; SELECT * FROM user", function (err, result, field){
    if (err){
         return console.log('error: ' + err.message);
    }

    res.render('patrol_schedule', {result: result, name: name});
});

The error message

 ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM user' at line 1

Upvotes: 0

Views: 1509

Answers (2)

JM_BJ
JM_BJ

Reputation: 51

var sql = "SELECT users.name AS user, products.name AS favorite FROM users JOIN products ON users.favorite_product = products.id";

Ref: https://www.w3schools.com/nodejs/nodejs_mysql_join.asp

Upvotes: 0

Barmar
Barmar

Reputation: 780879

You can't do two queries in one call to connection.query(). Do the second query in the callback function of the first.

connection.query("SELECT * FROM patrols", function(err, patrol_result) {
  if (err) {
    return console.log('error: ' + err.message);
  }
  connection.query("SELECT * FROM user", function(err, user_result) {
    if (err) {
      return console.log('error: ' + err.message);
    }
    res.render('patrol_schedule', {
      patrol: patrol_result,
      user: user_result
    });
  });
});

Upvotes: 1

Related Questions