2

How to write long MySQL queries on many lines instead of one very long line for easy reading and modifying. I only know this way to write them:

app.get('/example', function(req, res){
  x = 'SELECT doctors_schedule.*, employees.employee_name, doctors.degree FROM doctors_schedule JOIN employees ON employees.employee_id = doctors_schedule.doctor_id JOIN doctors ON doctors.doctor_id = employees.employee_id ORDER BY employees.employee_id';
  connection.query(x, function(error, rows, fields){
    if(error){console.log(error);}
    res.json(rows);
  });
});

2 Answers 2

2

Use template literals (template strings):

app.get('/example', function(req, res){
  const x = `SELECT doctors_schedule.*, employees.employee_name, doctors.degree 
    FROM doctors_schedule
    JOIN employees ON employees.employee_id = doctors_schedule.doctor_id
    JOIN doctors ON doctors.doctor_id = employees.employee_id
    ORDER BY employees.employee_id`;

  connection.query(x, function(error, rows, fields){
    if(error){
      console.log(error);
    }
    res.json(rows);
  });
});

This feature is available since Node.js v.4.0.0.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I can not imagine that it is that simple
1

es6 brought us template literals. You can use backticks, and span multiple lines easily. Read more about this here:

app.get('/example', function(req, res){
  x = `
     SELECT doctors_schedule.*, employees.employee_name, doctors.degree
     FROM doctors_schedule
     JOIN employees ON employees.employee_id = doctors_schedule.doctor_id
     JOIN doctors ON doctors.doctor_id = employees.employee_id
     ORDER BY employees.employee_id
  `;
  connection.query(x, function(error, rows, fields){
    if(error){console.log(error);}
    res.json(rows);
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.