Search code examples
sqldatabasewebmultiple-select

Is it possible to optimize these 2 select statements into one?


Select 1 
from Friend 
where Friend.UserID = 1 
  and FriendID = (select User.UserID from User where UserName = 'friend_user');

What I'm trying to do is to check whether a user is "friends" with another user. So when the user navigates to "foo.com/user/username" the username is passed and that's when I do the check. I would prefer to not use two selects but it seems that's the only way to do this. Any suggestions to the best way of doing a task like this would be appreciated.


Solution

  • You could use a JOIN instead:

    Select 1 
    from Friend f
    join User u
        on f.FriendID = u.UserID
        and u.UserName = 'friend_user'
    where 
        f.UserID = 1;