[英]node mysql if select gets results, return the results, else do a different select and return those results
我有2條語句可以很好地與MySQL數據庫對話。 兩者都存儲在aSQL和bSQL等變量中。
因此,我嘗試執行以下操作,如果查詢中存在任何記錄,則返回aSQL,否則從bSQL返回結果。
let sql = `
IF (${aSQL}) THEN
BEGIN
${aSQL};
END;
ELSE
BEGIN
${bSQL};
END;
END IF;
`
我還嘗試了另一篇SO帖子中的以下內容(將WHERE替換為AND,因為我的查詢已包含WHERE):
let sql = `
with temp as (${aSQL})
select * from temp
union all
${bSQL} AND (select count(*) from temp) =0
`
乃至:
let sql = `SELECT IF(EXISTS(${aSQL}), 1, 0) ELSE ${bSQL}`
沒關系,我明白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
。
但是,如果我只是做connection.query(aSQL)
或connection.query(bSQL)
它就可以工作。
如何在單個查詢中做到這一點而又不將過程永久存儲在數據庫中?
對於非js開發人員,請注意, sql = `${aSQL}`
只是一個模板,它輸入var aSQL
完整字符串值,該值可能等於SELECT * FROM db.table WHERE id=60 AND other=foo
。
只是等待結果,如果結果為空,請執行下一個查詢:
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.