如何在节点JS中编写长MySQL查询

时间:2018-07-25 20:44:48

标签: mysql node.js express

如何在多行而不是一长行上编写长MySQL查询,以便于阅读和修改。 我只知道这种写方式:

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 个答案:

答案 0 :(得分:0)

使用template literals(模板字符串):

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);
  });
});

此功能自Node.js v.4.0.0起可用。

答案 1 :(得分:0)

es6为我们带来了模板文字。您可以使用反引号,并轻松跨越多行。进一步了解此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);
  });
});