0

I have 2 tables , Users and Friends Table, Users have uID, Friends have UID as well, I want to check the UIDs present in Users table but not present in Friends Table, I am using this query

SELECT b.userId 
FROM users b 
where b.userId NOT IN(
  select userId 
  from user_friend
)

But it is returning me all the rows of Users Table.. Am I missing something? Example Data in MYSQL

Users Table
1
2
3
4
Friends Table
2
3
4

I actually need to get 1

3 Answers3

1

Try this

SELECT b.userId 
FROM users b 
WHERE NOT EXISTS (
   SELECT * 
   FROM user_friend
   WHERE b.userId = user_friend.userId
);
Tippa Raj
  • 584
  • 4
  • 8
  • #1064 - 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 'EXISTS ( SELECT * FROM user_friend ) LIMIT 0, 30' at line 3 –  Oct 21 '13 at 09:36
  • @TippaRaj It would have been better, if an explanation was given on why the `NOT IN` did not work. – Ravinder Reddy Oct 21 '13 at 09:47
0

Try this one:

SELECT b.userId 
FROM users b 
where b.userId NOT IN(
  select user_friend.userId 
  from user_friend
)
Taemyr
  • 3,407
  • 16
  • 26
Max
  • 33
  • 6
0

A Work Around for your query

SELECT  U.UserId
FROM    Users U
EXCEPT
SELECT  F.UserId
FROM    Friends F
Gopesh Sharma
  • 6,730
  • 4
  • 25
  • 35