2013-07-19 89 views
0

這是我的查詢來獲取用戶的朋友。但有一個問題。如果接收者是會話用戶,它將以朋友身份返回自己。排除友誼頁面 - MySQL

SELECT user.name_surname, user.id, friendship.receiver_id, friendship.sender_id 
FROM user 
JOIN friendship ON user.id = friendship.receiver_id 
WHERE 
    (friendship.receiver_id =".$_SESSION["SES_USER_ID"]." OR friendship.sender_id =".$_SESSION["SES_USER_ID"].") 
    AND is_approved='1'" 

下表是我的MySQL表設計。我已登錄爲user_id =16到網站。然後user_id=19寄給我一個朋友的請求。然後我批准了它。這裏的一切都很美,但是當我想看到我的朋友時,我也把自己看作是我的朋友。

如何在朋友頁面排除自己?

friendship table


嘗試以下

如果我改變這一行

JOIN friendship ON user.id = friendship.receiver_id 

TO

JOIN friendship ON user.id = friendship.sender_id 

這次向我發送友誼請求的另一個用戶將他/她的自己視爲他/她的朋友。

回答

0
SELECT user.name_surname, user.id, friendship.receiver_id, friendship.sender_id 
FROM user 
JOIN friendship ON user.id = friendship.sender_id OR user.id = friendship.receiver_id 
WHERE (friendship.receiver_id =".$_SESSION["SES_USER_ID"]." OR friendship.sender_id =".$_SESSION["SES_USER_ID"].") 
AND is_approved='1' 
AND user.id != ".$_SESSION["SES_USER_ID"]." 
+0

我解決了它,就像上面 – hakiko

+0

很高興你解決了它。 – amaster

0

"AND user.id != " . $_SESSION["SES_USER_ID"] 

不能做?所以,你的整個查詢將是:

SELECT user.name_surname, user.id, friendship.receiver_id, friendship.sender_id 
FROM user 
JOIN friendship ON user.id = friendship.receiver_id 
WHERE (friendship.receiver_id =".$_SESSION["SES_USER_ID"]." OR friendship.sender_id =".$_SESSION["SES_USER_ID"] . ") 
AND is_approved='1' 
AND user.id != " . $_SESSION["SES_USER_ID"] 

編輯: 我覺得您的查詢應該是:

SELECT user.name_surname, user.id, friendship.receiver_id, friendship.sender_id 
FROM user 
JOIN friendship ON user.id = friendship.receiver_id 
AND friendship.receiver_id != " . $_SESSION['SES_USER_ID'] . " 
WHERE (friendship.receiver_id =".$_SESSION["SES_USER_ID"]." OR friendship.sender_id =".$_SESSION["SES_USER_ID"] . ") 
AND is_approved='1' 
+0

如果我只添加此查詢將返回所有用戶user表! – hakiko

+0

您需要將其添加到您已有的內容中。 – mavili

+0

我知道下面的回答者也談到了這個問題,但它在回憶中注意到。其實我有一個朋友 – hakiko