2014-05-20 31 views
1

標題有點尷尬,但我會盡我所能解釋我想要完成的事情。MySQL連接類型爲同一表中的記錄

我有一個名爲Users的表格和另一個名爲Friends的表格。

Users表的抽象結構爲:

+----+------+----------+----------+ 
| ID | Name | Username | Password | 
+----+------+----------+----------+ 

Friends表有一個抽象的結構,如:

+----+--------+----------+--------+ 
| ID | UserID | FriendID | Hidden | 
+----+--------+----------+--------+ 

UserID是誰發送了好友請求的用戶的ID並且FriendID是請求的接收者。如果收件人選擇隱藏請求,則隱藏列的值將爲1。

我想壓縮這一切到一個查詢,到目前爲止,我有兩個單獨的使用LEFT JOINRIGHT JOIN

要找到發出的請求和現在的朋友:

SELECT 
    *, 
    CASE 
     WHEN C.ID IS Null THEN "Request Sent" 
     ELSE "Friends" 
    END AS Status 
FROM 
    (SELECT DISTINCT 
     A.ID, A.Name, E.Hidden 
    FROM 
     Users A 
    INNER JOIN 
     Friends E ON A.ID = E.UserID 
    WHERE 
     A.ID in (SELECT UserID 
        FROM Friends 
        WHERE FriendID = "1" AND Deleted='No')) C 
RIGHT JOIN 
    (SELECT DISTINCT 
     B.ID, B.Name, F.Hidden 
    FROM 
     Users B 
    INNER JOIN 
     Friends F ON B.ID = F.FriendID 
    WHERE 
     B.ID in (SELECT FriendID 
        FROM Friends 
        WHERE UserID = "1" AND Deleted = 'No')) D ON C.ID = D.ID 

至於好友請求接收電流的朋友:

SELECT *, CASE WHEN D.ID IS Null THEN "Wants to be your friend" ELSE "Friends" END AS Status FROM 
(SELECT DISTINCT 
A.ID, A.Name, E.Hidden 
FROM 
Users A INNER JOIN Friends E ON A.ID=E.UserID 
WHERE 
A.ID in (SELECT UserID FROM Friends WHERE FriendID = "1" AND Deleted='No')) C 
LEFT JOIN 
(SELECT DISTINCT 
B.ID, B.Name, F.Hidden 
FROM 
Users B INNER JOIN Friends F ON B.ID=F.FriendID 
WHERE 
B.ID in (SELECT FriendID FROM Friends WHERE UserID = "1" AND Deleted='No')) D 
ON C.ID=D.ID 

維恩圖下面可能是一個重要的說明推,如果我沒有解釋我需要什麼。

Venn Diagram

請注意,爲構建我選擇的所有列querie(S)的目的,但我將只需要在最後的朋友的名字和ID的。

回答

1

做兩個查詢之間的union allunion distinct這將返回一個表中的所有結果。

SELECT *, D.ID, CASE WHEN D.ID IS Null THEN "Wants to be your friend" ELSE "Friends" END AS Status FROM 
(SELECT DISTINCT 
A.ID, A.Name, E.Hidden 
FROM 
Users A INNER JOIN Friends E ON A.ID=E.UserID 
WHERE 
A.ID in (SELECT UserID FROM Friends WHERE FriendID = "1" AND Deleted='No')) C 
LEFT JOIN 
(SELECT DISTINCT 
B.ID, B.Name, F.Hidden 
FROM 
Users B INNER JOIN Friends F ON B.ID=F.FriendID 
WHERE 
B.ID in (SELECT FriendID FROM Friends WHERE UserID = "1" AND Deleted='No')) D 
ON C.ID=D.ID 
union all 
SELECT *, D.ID, CASE WHEN C.ID IS Null THEN "Request Sent" ELSE "Friends" END AS Status FROM 
(SELECT DISTINCT 
A.ID, A.Name, E.Hidden 
FROM 
Users A INNER JOIN Friends E ON A.ID=E.UserID 
WHERE 
A.ID in (SELECT UserID FROM Friends WHERE FriendID = "1" AND Deleted='No')) C 
RIGHT JOIN 
(SELECT DISTINCT 
B.ID, B.Name, F.Hidden 
FROM 
Users B INNER JOIN Friends F ON B.ID=F.FriendID 
WHERE 
B.ID in (SELECT FriendID FROM Friends WHERE UserID = "1" AND Deleted='No')) D 
ON C.ID=D.ID 
+0

在將'UNION ALL'更改爲'UNION DISTINCT'來停止重複行,如果兩個用戶是朋友後,似乎工作。感謝您的幫助! –

+0

又一個額外的位,是否可以提供用戶的ID,在這個問題中是1,只有一次?這只是我有一個會話表,所以我將使用內部聯接語句從他們的會話ID獲取用戶標識。不過,雖然沒有! –

+0

你不是已經有一個案例結構來判斷這是否是1嗎? – Hituptony

相關問題