mysql - 如何正确执行sql查询(node.js + express)

标签 mysql node.js express

在数据库中,我有两个表:包含所有用户注册详细信息的用户和包含用户 friend 关系数据的 friend (friend_one、friend_two 是引用 users.user_id 的外键)、状态(0 - 期望,1 - 拒绝, 2 - 接受) 和时间戳。 friend_one - 始终是友谊的发起者。女生只能加男生好友,男生只能加女生好友。因此,当我尝试获取用户的 friend 数量时 - 例如,id 为 5 的男孩: enter image description here

exports.amountOfFriends = function (req, res) {
    var user =  req.session.user,
    userId = req.session.session_id;
    if(userId == null){
       res.redirect("/login");
       return;
    }
   let sql = `SELECT COUNT(*) myCount FROM friends WHERE status = ? AND friends_one =? OR friends_two =? `;
   let post = [2, userId, userId];
    connection.query(sql, post, (err, result) => {
        if(err){
            console.log(err)
        }
        res.json(result);
        console.log(result[0].myCount);

    });

};

我得到值 - 2。但正确的值是 3。因为 ID 为 5 的用户有三个 friend 。请帮我解决这个问题。 enter image description here

enter image description here

enter image description here

最佳答案

您需要围绕两个 OR 条件的 ()

 `SELECT COUNT(*) myCount FROM friends
   WHERE status = ? AND ( friends_one =? OR friends_two =?) `;

关于mysql - 如何正确执行sql查询(node.js + express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48986808/

相关文章:

MySQL 程序中出现错误 "Truncated incorrect DOUBLE value"

mysql - 从另一个域访问drupal mysql

mysql - 在crontab centos中发送Email on Sql报错

javascript - readFile 未在 while 循环内运行

express - 使用 aws elastic beantalk 将非 www 重定向到 www

php - 显示用户登录数据

javascript - 将更改推送到已部署的 Meteor.js 应用程序

javascript - Node.js + Express + MySQL 作为文档存储(结果)

json - 使用 Watson API Nodejs 分析 json

json - 使用 Express 4 在 Node.js 中解析 JSON 发布请求