2010-06-03 123 views
3

我有一個包含用戶ID &他的朋友們想要開個表:MySQL的:INNER JOIN

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

此表的數據顯示,用戶1 &用戶-2是朋友&他們也有frndship與用戶3 。 現在我想找到其中用戶ID 1個&用戶ID 2普通朋友(個),如: 在森坦斯我的查詢:用戶1 &用戶2有1個普通朋友FriendId 3.

爲此,我使用SQL查詢INNER JOIN:

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

,但不能退貨要求的結果..

回答

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

編輯

-1

請試試這個

select u1.FriendId 
from userfriends u1 
inner join userfriends u2 on u1.FriendId = u2.FriendId 
where u1.UserId = 1 and u2.UserId = 2 
+0

-1該報告用戶1的兩倍! – lexu 2010-06-03 06:23:19

+0

我不明白。這有什麼問題。 – Sujee 2010-06-03 06:32:05

+0

@Sujee:在我的回覆下面看到我對你評論的回答..我正在取消倒票。 – lexu 2010-06-03 08:29:47

0

嘗試此查詢(非常類似於TH別人貼)

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 

要注意的是這個報告每友誼鏈的兩倍,一旦你刪除了絕對的ID。爲了避免這種情況,我要求T1.UserID比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) 
+0

您如何看待它會報告兩次? 檢查這些條款't1.UserId = 2和T2.userId = 1'。 然後檢查'(T1.userID T2.userID)'是無用的。 – Sujee 2010-06-03 06:33:42

+0

@Sujee:BANG(手擊中的頭)**你是對的**我一直在想太多的一般情況!我的appologies! – lexu 2010-06-03 08:28:50

+0

@lexu沒問題。有時候,這也發生在我身上! – Sujee 2010-06-03 09:32:04

0
SELECT table1.name, table2.salary 
    FROM employee AS table1 INNER JOIN info AS table2 ON table1.name = table2.name;