Reputation: 2483
I am trying to call javascript variables from within the mySQL query. The lines are executed with node.js environment, using syntax [node (filename)]. I understand that I could potentially do this query in 2 steps, by first query the value of min_value, and then query the max_value.
Can the request be executed in one mySQL query?
Preferably I would like to keep the code structure with vanilla js and mySQL, without adding node.js-specific commands, nor needing to load extra packages.
Javascript variables:
let min_value = 100;
let max_value = 300;
This works:
sql = `
SELECT
acronym,
salaries
FROM
employees
WHERE
salaries BETWEEN 100 and 300
ORDER BY acronym;
`;
This does not works:
sql = `
SELECT
acronym,
salaries
FROM
employees
WHERE
salaries BETWEEN ($min_value) and ($max_value)
ORDER BY acronym;
`;
Upvotes: 0
Views: 70
Reputation: 577
Try using Template Literals, with the ${variable}
placeholder syntax:
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);
Upvotes: 3