2013-03-22 226 views
0

我要連接兩個包含另一個表中的兩列的表。MySQL連接來自兩列的兩個表

表用戶

id | first_name | last_name | 
---+------------+-----------+ 
1 | John  | Doe  | 
2 | Jane  | Doe  | 
3 | Some  | Name  | 

表郵票

id | date | applicant_id | app_by_id | 
---+------------+---------------+-----------+ 
1 | 2013-03-15 | 1    | 2   | 
2 | 2013-03-10 | 2    | 3   | 
3 | 2013-03-13 | 2    | 1   | 

我想要什麼顯示:

date | applicant | app_by | 
------------+-----------+-----------+ 
2013-03-15 | John Doe | Jane Doe | 
2013-03-10 | Jane Doe | Some Name | 
2013-03-13 | Jane Doe | John Doe | 

我的查詢:

SELECT CONCAT_WS(' ', NULLIF(t1.first_name, ' '), NULLIF(t1.last_name, ' ')) AS applicant, 
    CONCAT_WS(' ', NULLIF(t1.first_name, ' '), NULLIF(t1.last_name, ' ')) AS app_by, 
    t2.date 
    FROM users t1 
    INNER JOIN stamp t2 ON applicant_id = t1.id 

我知道我的查詢有問題,但我不知道如何解決它。

回答

0

你可能想使用LEFT JOIN讓你在即使其它連接條件未能每一列獲取值。以下代碼也適用於常規的JOIN

SELECT s.date, 
CONCAT_WS(' ', NULLIF(u1.first_name, ' '), NULLIF(u1.last_name, ' ')) AS applicant, 
CONCAT_WS(' ', NULLIF(u2.first_name, ' '), NULLIF(u2.last_name, ' ')) AS app_by 
FROM stamp s 
LEFT JOIN users u1 ON s.applicant_id = u1.id 
LEFT JOIN users u2 ON s.app_by_id = u2.id 

證明:http://sqlfiddle.com/#!2/39aff/1/0

+0

謝謝。這是我需要的答案。 – otezz 2013-03-22 09:12:02

0

試試你的加入像

SELECT CONCAT_WS(' ', NULLIF(u1.first_name, ' '), NULLIF(u1.last_name, ' ')) AS applicant, 
     CONCAT_WS(' ', NULLIF(u2.first_name, ' '), NULLIF(u2.last_name, ' ')) AS app_by, 
     s.date 
FROM stamp s INNER JOIN 
     user u1 ON s.applicant_id = u1.id INNER JOIN 
     user u2 ON s.app_by_id = u1.id 
+0

@AdamPlocher是,糾正它感謝 – 2013-03-22 04:59:47

0

而是加入的,儘量使用子查詢這個樣子。

SELECT date, 
(SELECT CONCAT_WS(' ', NULLIF(first_name, ' '), NULLIF.last_name, ' ')) from USERS WHERE id = s.applicant_id) as applicant, 
(SELECT CONCAT_WS(' ', NULLIF(first_name, ' '), NULLIF.last_name, ' ')) from USERS WHERE id = s.app_by_id) as app_by 
from stamp s