我正在尝试从mySQL查询中调用javascript变量。
这些行在node.js环境中使用语法[node(filename)]执行。我了解我可以分两步执行此查询,方法是先查询min_value的值,然后查询max_value。

可以在一个mySQL查询中执行请求吗?

最好是,我希望保留香草js和mySQL的代码结构,而无需添加特定于node.js的命令,也不需要加载额外的程序包。

JavaScript变量:

let min_value = 100;
let max_value = 300;


这有效:

sql = `
 SELECT
   acronym,
   salaries
 FROM
   employees
 WHERE
   salaries BETWEEN 100 and 300
ORDER BY acronym;
`;


这不起作用:

sql = `
 SELECT
   acronym,
   salaries
 FROM
   employees
 WHERE
   salaries BETWEEN ($min_value) and ($max_value)
ORDER BY acronym;
`;

最佳答案

尝试使用Template Literals${variable}占位符语法:



let min_value = 100;
let max_value = 300;
let sql1 = `
 SELECT
   acronym,
   salaries
 FROM
   employees
 WHERE
   salaries BETWEEN (${min_value}) and (${max_value})
ORDER BY acronym;
`;

let sql2 = `
 SELECT
   acronym,
   salaries
 FROM
   employees
 WHERE
   salaries BETWEEN ${min_value} and ${max_value}
ORDER BY acronym;
`;

console.log(sql1);
console.log(sql2);

10-07 15:59