2012-12-09 124 views
2

讓我們說我有MySQL的加入2個表,2列

student_data和字段

 

╔════╦════════════╦════════════╗ 
║ ID ║ CREATED_BY ║ UPDATED_BY ║ 
╠════╬════════════╬════════════╣ 
║ 1 ║   1 ║   2 ║ 
╚════╩════════════╩════════════╝ 

creator_updater和字段

 

╔════╦════════════════╗ 
║ ID ║  NAME  ║ 
╠════╬════════════════╣ 
║ 1 ║ The Creator ║ 
║ 2 ║ Second Creator ║ 
╚════╩════════════════╝ 

所以我不知道什麼是確切的代碼所以它會顯示

 
student_data 

╔════╦═══════════════╦══════════════════════╗ 
║ ID ║ CREATED_BY_ID ║ LATEST_UPDATED_BY_ID ║ 
╠════╬═══════════════╬══════════════════════╣ 
║ 1 ║ The Creator ║ Second Creator  ║ 
╚════╩═══════════════╩══════════════════════╝ 

我試過加入語法,但看起來不同

回答

3

您需要兩次加入creator_updater表,因此您可以獲取兩列的名稱。

SELECT a.id, 
     b.name created_by_id, 
     c.name latest_updated_by_id 
FROM student_data a 
     INNER JOIN creator_updater b 
      ON a.created_by = b.id 
     INNER JOIN creator_updater c 
      ON a.updated_by = c.id 

但代碼,如果其中一列是可空,如果是這樣的話,使用的LEFT JOIN代替INNER JOIN

SELECT a.id, 
     b.name created_by_id, 
     c.name latest_updated_by_id 
FROM student_data a 
     LEFT JOIN creator_updater b 
      ON a.created_by = b.id 
     LEFT JOIN creator_updater c 
      ON a.updated_by = c.id 

有關更多信息加入

+0

是啊,這就是我說的。感謝兄弟,我會再問我是否有問題 –