node mysql如果select获取结果,返回结果,否则执行不同的select并返回结果

时间:2017-10-25 23:16:39

标签: mysql node-mysql

在与MySQL db交谈时,我有2个单独运行的语句。两者都存储在aSQL和bSQL等变量中。

所以我正在尝试执行以下操作,如果查询中存在任何记录,则返回aSQL,否则返回bSQL的结果。

let sql = `
IF (${aSQL}) THEN
BEGIN
    ${aSQL};
END;
ELSE
BEGIN
    ${bSQL};
END;
END IF;
`

我还尝试了another SO post中的以下内容(将AND替换为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

但如果我只是做connection.query(aSQL)connection.query(bSQL)就行了。

如何在单个查询中执行此操作而不在数据库中永久存储过程?

非js开发人员的注意事项sql = `${aSQL}`只是一个模板,并输入var aSQL的完整字符串值,可能等于SELECT * FROM db.table WHERE id=60 AND other=foo

2 个答案:

答案 0 :(得分:1)

找到solution here

let sql = `${aSQL} UNION ALL ${bSQL} AND NOT EXISTS (${aSQL})`

aSQLbSQL类似于以下内容:

SELECT * FROM db.table WHERE id=60 AND other=foo
SELECT * FROM db.table WHERE id=47 AND other=bar

答案 1 :(得分:0)

只是等待结果,如果结果为空,则执行下一个查询:

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)
    }    
 });