I have 2 statements that work fine alone when talking to MySQL db. Both stored in variables like aSQL and bSQL.
So i'm trying to do the following where i return aSQL if any records from the query exist, else return the results from bSQL.
let sql = `
IF (${aSQL}) THEN
BEGIN
${aSQL};
END;
ELSE
BEGIN
${bSQL};
END;
END IF;
`
I also tried the following from another SO post (replaced WHERE with AND because my query already has a WHERE):
let sql = `
with temp as (${aSQL})
select * from temp
union all
${bSQL} AND (select count(*) from temp) =0
`
And even:
let sql = `SELECT IF(EXISTS(${aSQL}), 1, 0) ELSE ${bSQL}`
No mater what, i get You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
.
But if i simply do connection.query(aSQL)
or connection.query(bSQL)
it works.
How do you do this in a single query without permanently storing a procedure in the db?
Note for non-js devs sql = `${aSQL}`
is just a template and inputs full string value of var aSQL
that might be equal to SELECT * FROM db.table WHERE id=60 AND other=foo
.