[英]node mysql if select gets results, return the results, else do a different select and return those results
I have 2 statements that work fine alone when talking to MySQL db. 我有2条语句可以很好地与MySQL数据库对话。 Both stored in variables like aSQL and bSQL. 两者都存储在aSQL和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. 因此,我尝试执行以下操作,如果查询中存在任何记录,则返回aSQL,否则从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): 我还尝试了另一篇SO帖子中的以下内容(将WHERE替换为AND,因为我的查询已包含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
没关系,我明白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
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
. 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. 但是,如果我只是做connection.query(aSQL)
或connection.query(bSQL)
它就可以工作。
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
. 对于非js开发人员,请注意, sql = `${aSQL}`
只是一个模板,它输入var aSQL
完整字符串值,该值可能等于SELECT * FROM db.table WHERE id=60 AND other=foo
。
Found the solution here : 在这里找到解决方案 :
let sql = `${aSQL} UNION ALL ${bSQL} AND NOT EXISTS (${aSQL})`
Where aSQL
and bSQL
look similar to the following: 其中aSQL
和bSQL
看起来类似于以下内容:
SELECT * FROM db.table WHERE id=60 AND other=foo
SELECT * FROM db.table WHERE id=47 AND other=bar
just wait for result, and if result is empty, execute next query: 只是等待结果,如果结果为空,请执行下一个查询:
connection.query(aSQL, function (err, result, fields) {
if (err || result == 0 || result.length == 0) {
connection.query(bSQL, function(err, result, fields){console.log(result)});
}else {
console.log(result)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.