2013-03-05 61 views
0

是否可以通過INNER JOIN一個MySQL查詢來實現這個結果?MySQL`INNER JOIN`同一表的倍數

我有一個表與策略和表與會員。 「策略」表包含與其成員表中的ID相對應的作者ID以及更新現有作者作品的作者ID。是否有可能同時獲得這兩個人的參考?像下面,不返回任何錯誤,但還沒有結果......

SELECT * FROM Strategies 
INNER JOIN Members AS a 
INNER JOIN Members AS b 
WHERE Strategies.ID='2' 
AND Strategies.AuthorID = a.ID 
AND Strategies.UpdateAuthorID = b.ID 

回答

4

使用LEFT JOIN

SELECT 
    s.*, 
    a.Name AS MemberName, 
    b.Name AS UpdatedMemberName 
FROM Strategies AS s 
LEFT JOIN Members AS a ON s.AuthorID = a.ID AND s.ID = 2 
LEFT JOIN Members AS b ON s.UpdateAuthorID = b.ID AND s.ID = 2 ; 

如果你希望他們在一列中使用COALESCE

SELECT 
    s.*, 
    COALESCE(a.Name, b.Name) AS MemberName 
FROM Strategies AS s 
LEFT JOIN Members AS a ON s.AuthorID = a.ID AND s.ID = 2 
LEFT JOIN Members AS b ON s.UpdateAuthorID = b.ID AND s.ID = 2 
+0

我只需要將值賦給我的php變量,這樣我就可以顯示它們。所以最重要的應該是正確的? – SnareChops 2013-03-05 07:01:23

+0

@SnareChops兩者都可以正常工作,第一個會爲您提供兩列'AuthorId',另一個列爲'UpdatedAuthorId',但第二個查詢只會給您一列;不可空的。 – 2013-03-05 07:15:40

4
SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 
    rvw.* 

FROM reviews AS rvw 

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for 

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from 

如果域名是表名