我正在尝试从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;
`;
答案 0 :(得分:3)
尝试使用${variable}
占位符语法使用Template Literals:
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);