【问题标题】:Query of MySQL database it does not work correctly with if conditional?如果有条件,它不能正常工作的 MySQL 数据库查询?
【发布时间】:2021-01-24 14:03:18
【问题描述】:

我想从 MySQL 数据库中选择值,如果值等于wait,则打印一些东西。这是简单的事情,但有条件它不能正常工作。

代码:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'DAGtest2'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Database Connected!');
});

connection.query("SELECT `message` FROM `counter` LIMIT 1", (err, check) => {
    if(err) throw err;
    console.log(check);

    if (check['message'] === "wait"){
        console.log("waiting....");

    } else {
        console.log("start counter...."); 
    }
});

输出:

Database Connected!
[ RowDataPacket { message: 'wait' } ]
start counter....

如果我删除 wait 消息仍然显示相同的输出:

Database Connected!
[]
start counter....

我尝试使用不相等的条件:

if (check['message'] !== "wait"){
    console.log("waiting....");

} else {
    console.log("start counter...."); 
}

输出:

Database Connected!
[ RowDataPacket { message: 'wait' } ]
waiting....

如果我也删除wait

Database Connected!
[]
waiting....

我想要的正确输出是当消息等于wait时,它必须打印waiting....,否则它必须打印start counter....。但是当我从表中删除wait 时,代码无法正常工作。

请问怎么解决?

【问题讨论】:

    标签: javascript mysql sql node.js if-statement


    【解决方案1】:

    将您的 sql 语句改写成更适合您的方式吗?

    SELECT message
    CASE
        WHEN message = 'wait' THEN 'waiting....'
        ELSE 'start counter....'
    END
    FROM counter; 
    

    【讨论】:

    • 感谢您的回答。不幸的是,我在 node.js 中需要它,因为console.log() 后面有几行,但我删除了它以使其变得简单。
    猜你喜欢
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    相关资源
    最近更新 更多