2010-07-08 143 views
9

我有一個user表和complaint表。在不同的列上加入同一個表兩次

complaint表的結構如下:

[opened_by] [complaint_text] [closed_by] 
(user_id)   (text)   (user_id) 
(user_id)   (text)   (user_id) 
(user_id)   (text)   (user_id) 

所有用戶,無論是抱怨投訴解析器位於表user

如何編寫查詢以顯示兩列的用戶名?

這給了我一個:

SELECT user.username, complaint.complaint_text 
FROM complaint 
LEFT JOIN user ON user.user_id=complaint.opened_by 

,但我不知道怎麼寫這樣既​​欄顯示用戶名,而不是標識。

回答

31
SELECT 
    complaint.complaint_text, 
    A.username, 
    B.username 
FROM 
    complaint 
    LEFT JOIN user A ON A.user_id=complaint.opened_by 
    LEFT JOIN user B ON B.user_id=complaint.closed_by 
+0

我更喜歡在可能的情況下進行子查詢,易於閱讀和高效。 – 2013-08-22 16:14:13

+0

這不會提供'抱怨'x'A' x'B'的笛卡爾產品嗎? – NeverEndingQueue 2017-11-28 16:24:14

+0

@NeverEndingQueue - 不會,因爲每個JOIN都有一個條件 – potatopeelings 2017-11-28 22:42:32

0
SELECT user1.username AS opened_by_username, complaint.complaint_text, user2.username AS closed_by_username 
FROM user AS user1, complaint, user as user2 
WHERE user1.user_id = complaint.opened_by 
AND user2.user_id = complaint.closed_by 

再次使用別名加入它(這就是用戶如user2的東西,是關於什麼的)

0

使用此查詢:

SELECT opener.username as opened_by, complaint.complaint_text, closer.username as closed_by 
FROM complaint 
LEFT JOIN user as opener ON opener.user_id=complaint.opened_by 
LEFT JOIN user as closer ON closer.user_id=complaint.closed_by 
1

我更喜歡子查詢,因爲我覺得他們更容易理解...

SELECT (SELECT name 
      FROM user 
      WHERE user_id = opened_by) AS opener, 
     (SELECT name 
      FROM user 
      WHERE user_id = closed_by) AS closer, 
     complaint_text 
    FROM complaint; 

如果您有任何性能問題,子查詢通常會被查詢優化器重寫。

相關問題