tags:

views:

50

answers:

4
+3  Q: 

MySQL: INNER JOIN

I have a table which contains UserId & his Friends Id like:

----------------------------------------------
UserFriendsId    |    UserId    |    FriendId
----------------------------------------------
     1                  1              2
----------------------------------------------
     2                  1              3
----------------------------------------------
     3                  2              1
----------------------------------------------
     4                  2              3
----------------------------------------------

This table data shows that User-1 & User-2 are friend & they also have frndship with User-3. Now I want to find common friend(s) among UserId 1 & UserId 2 for eg: In sentance my query is: User 1 & User 2 have 1 common Friend FriendId 3.

For this I used SQL query for INNER JOIN:

SELECT t1.* 
  FROM userfriends t1 
 INNER JOIN userfriends t2 
    ON t1.FriendId = t2.FriendId 
 WHERE t1.UserId = 2

But not return required result..

+1  A: 
select * 
  from MyTable as A
 inner join MyTable as B 
    on     (A.UserID = 1 and B.UserID = 2)
       and (A.FriendID = B.FriendID)

edited

hamlin11
A: 

Please try this

select u1.FriendId
from userfriends u1
inner join userfriends u2 on u1.FriendId = u2.FriendId
where u1.UserId = 1 and u2.UserId = 2
Sujee
-1 this reports user 1 twice!
lexu
I don't understand. What is wrong with this.
Sujee
@Sujee: See my answer to your comment below my reply .. I'm removing the down-vote.
lexu
Thank you @lexu
Sujee
A: 

Try this query (very similar to th others posted)

SELECT t1.UserID,T2.userID,T1.FriendID 
  FROM userfriends t1 
  JOIN userfriends t2 
    ON     (t1.FriendId = t2.FriendId )
       and (T1.userID <>T2.userID)
 WHERE t1.UserId = 2 
   and T2.userId=1

Beware that this reports every friendship-chain twice once you remove the absolute IDs. To avoid that I ask that T1.UserID be smaller than T2.userID:

SELECT t1.UserID,T2.userID,T1.FriendID 
  FROM userfriends t1 
  JOIN userfriends t2 
    ON     (t1.FriendId = t2.FriendId )
       and (T1.userID < T2.userID)
lexu
How do you think it will report twice?Check these clause `t1.UserId = 2 and T2.userId=1`.Then checking `(T1.userID < T2.userID)` or `(T1.userID <>T2.userID)` are useless.
Sujee
@Sujee: BANG (hand hit's head.) **You are right** I was thinking too much bout the general case! My appologies!
lexu
No problem @lexu. Sometimes this happens to me too!
Sujee
A: 
 SELECT table1.name, table2.salary
  FROM employee AS table1 INNER JOIN info AS table2 ON table1.name = table2.name;
bachchan