2017-08-07 61 views
0

我有兩個表User和relationshp。我需要找到所有發送登錄用戶朋友請求的用戶。需要找到一個查詢來返回MySQL中的某個結果

User Table      relationship Table 
------------   ---------------------------------------------- 
id | username   user_one_id | user_two_id | status | action_user_id 

這些是我的兩個表格。 user_one_id是發送請求的用戶,而user_two_id是收件人。

我需要找到一個查詢,它將返回登錄用戶收到的所有朋友請求。

如果嘗試以下操作,但它只返回登錄用戶的名稱和向其發送請求的用戶的ID。沒有返回發件人的姓名。

var loggedInUser = req.user[0]; 
connection.query(" 
SELECT User.id, User.username, relationship.user_one_id, 
relationship.status 
FROM User INNER JOIN relationship ON User.id=relationship.user_one_id 
WHERE User.id = ?", 
[loggedInUser], function(err, results, fields) {} 

任何幫助將不勝感激。

回答

0

您需要使用您的查詢的兩個INNER JOIN語句,一個用於user_one_id,另一個用於user_two_id

SELECT userA.id, userA.username, userB.id, userB.username, status, action_user_id 
FROM relationship 
INNER JOIN User AS userA ON userA.id = relationship.user_one_id 
INNER JOIN User AS userB ON userB.id = relationship.user_two_id 
WHERE userA.id = ? 

修訂答:

在這裏看到的鏈接瞭解詳情:http://sqlfiddle.com/#!9/af7ce/5

SELECT userA.id AS userA_id, userA.username AS userA_username, userB.id AS userB_id, userB.username AS userB_username, status, action_user_id, userC.username AS action_user_username 
FROM relationship 
INNER JOIN User AS userA ON userA.id = relationship.user_one_id 
INNER JOIN User AS userB ON userB.id = relationship.user_two_id 
INNER JOIN User AS userC ON userC.id = relationship.action_user_id 
WHERE (userA.id = 1 OR userB.id = 1) AND userC.id != 1 
+0

我試過查詢,它返回的結果與我第一次運行的查詢。試圖鼓搗它。謝謝你嘗試。 – psingh24

+0

好的答案已經更新了,我剛剛意識到你編輯了你最初的問題以包含更多細節。 – dat3450

+1

非常感謝!完美的作品! – psingh24

相關問題