2013-10-23 129 views
6

我有一個引用另一個表的ID的兩個字段的表。我需要從另一個表中爲這兩個字段取名。Mysql多個左邊的連接在同一張桌子上

例如。

 
Table1 
worker1 = 2 (2 is key to other table) 
worker2 = 4

Table2 ID NAME 1 Bill 2 Fred 3 John 4 Paul

我需要得到$ worker1name = Fred和$ worker2name = Paul。

所以我會說是這樣的:

SELECT xxx, NAME?, NAME? FROM Table1 
LEFT JOIN Table2 AS p1 ON Table1.worker1 = Table2.ID 
LEFT JOIN Table2 AS p2 ON Table1.worker2 = Table2.ID 
WHERE ... 

$table = mysql_query(...); 
$rec = mysql_fetch_assoc($table); 
$worker1name = $rec['???']; 
$worker2name = $rec['???']; 

什麼我提到的最後兩個語句插入拿到兩個名字。或者更確切地說,我必須添加到SELECT以指定我希望表2中名稱字段的兩個不同版本被調用的內容?

回答

15

你應該別名領域也是這樣:

SELECT 
    xxx, 
    p1.NAME as p1name, 
    p2.NAME as p2name 
FROM Table1 
LEFT JOIN Table2 AS p1 ON Table1.worker1 = p1.ID 
LEFT JOIN Table2 AS p2 ON Table1.worker2 = p2.ID 
WHERE ... 
+0

我得到一個錯誤:無法運行查詢:未知列「Table2.ID」在「關於條款」(在相當於我的名字表) – user2605793

+0

修改了查詢。 (你必須使用別名是有的。) –

+0

有幫助!謝謝 :) – InspiredCoder

-1
SELECT xxx, p1.NAME AS p1Name, p2.NAME AS p2Name FROM Table1 


$worker1name = $rec['p1Name']; 
$worker2name = $rec['p2Name'];