title: Multiple mysql queries with Express Node
body: <p>I am running an Express server and connecting to MySQL Database. I am have two tables  which are referenced via the <code>user_id</code>. When the user provides the email address I need to query <code>users</code> to find the <code>user_id</code> then run another query to join the <code>tracking</code> tables. What is the best way to achieve this? Also any best practice recommendations for any part of the code is appreciated!</p>
  
  <p>Thanks</p>
  
  <p>MySQL</p>
  
  <pre><code>CREATE TABLE users (
    user_id INT NOT NULL AUTO_INCREMENT UNIQUE,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) DEFAULT NULL,
    email VARCHAR(320) NOT NULL UNIQUE,
    date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id)
  );
  
  CREATE TABLE tracking (
    tracking_id INT NOT NULL AUTO_INCREMENT,
    user_id INT NOT NULL,
    metric VARCHAR(100) NOT NULL,
    unit VARCHAR(100) NOT NULL,
    amount DOUBLE DEFAULT NULL,
    date_tracked DATE,
    date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (tracking_id),
    INDEX user_ind (user_id),
    FOREIGN KEY (user_id)
     REFERENCES users(user_id)
     ON DELETE CASCADE
  );
  </code></pre>
  
  <p>Express (Nodejs)</p>
  
  <pre><code>const express = require("express");
  const app = express();
  const port = 3000;
  var mysql = require("mysql");
  var connection = mysql.createConnection({
    host: "",
    user: "",
    password: "",
    database: "tracker"
  });
  
  app.get("/data/:email/metric/:metric", (req, res) =&gt; {
    console.log(req.params);
    let user_id = "";
  
    connection.connect();
  
    connection.query(
      `SELECT user_id FROM users WHERE email = '${req.params.email}';`,
      function(error, results, fields) {
        if (error) throw error;
        user_id = results[0].user_id;
      }
    );
  
    connection.query(
      `SELECT users.first_name, users.last_name, users.email, tracking.metric, tracking.unit, tracking.amount, tracking.date_tracked FROM users JOIN tracking ON users.user_id = tracking.user_id WHERE users.user_id = '${user_id}' AND metric = '${
        req.params.metric
      }';`,
      function(error, results, fields) {
        if (error) throw error;
        res.send(results);
      }
    );
  
    connection.end();
  });
  
  app.listen(port, () =&gt; console.log(`Example app listening on port ${port}!`));
  </code></pre>