1

On database I have two tables: users which contains all the user registration details and friends which contains user friends relation data (friend_one, friend_two are the FOREIGN KEYs to references users.user_id), status (0 - expectation, 1 - denied, 2 - accepted) and timestamp. friend_one - is always initiator of friendship. Girls can add to friends only boy and boys can add only girls. So when i try get amount of friends of user - boy with id 5 for example : 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);

    });

};

I get value - 2. But correct value is 3. Because user with id 5 has three friends. Please help me fix this problem. enter image description here

enter image description here

enter image description here

4
  • 1
    you just miss bracket Commented Feb 26, 2018 at 10:58
  • when I add bracket I get value zero( Commented Feb 26, 2018 at 11:05
  • Can you run below ans to your mysql ? Commented Feb 26, 2018 at 11:08
  • Yes, and I still get zero Commented Feb 26, 2018 at 11:33

1 Answer 1

3

You neeed a () around the twor OR condition

 `SELECT COUNT(*) myCount FROM friends
   WHERE status = ? AND ( friends_one =? OR friends_two =?) `;
Sign up to request clarification or add additional context in comments.

9 Comments

I check, and I still get zero(
which data type are the columns status, friend_one, friend_two ..??
@scaisEdge, friend_one and friend two is integer, status is ENUM ('0','1','2')
i have tested the code in my db and work correctly .. just for test try execute the equivalente query SELECT COUNT(*) myCount FROM friends WHERE ( status = 2 AND friends_one =5) OR ( status = 2 AND friends_two 5) ;
are you sure you are connected related to the correct data source?? . seems that your table have not the expected data
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.