2011-11-14 27 views
4

我想要使用相同的列名聯接兩個表。我有我試圖連接兩個表,但我不斷收到錯誤:如何使用相同的列名聯接兩個表

column 'id' is ambiguous 

在我的JSON輸出返回。

我當前的查詢:

$sQuery = " 
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))." 
FROM $sTable 
LEFT JOIN 
    $sTable2 
    ON ($sTable2.id = $sTable.id) 

$sWhere 
$sOrder 
$sLimit 
"; 

產生錯誤。當每個表中有相同的列名時,如何將這兩個表作爲連接點?

回答

14

明確指出該列所屬的表。這也適用於查詢的SELECT部分​​:

SELECT table1.column AS column1, table2.column AS column2 
FROM table1 
LEFT JOIN table2 
ON table1.column = table2.column 

爲了節省您的打字時間,使用表別名:

SELECT t1.column AS column1, t2.column AS column2 
FROM table1 AS t1 
LEFT JOIN table2 AS t2 
ON t1.column = t2.column 
+0

謝謝...令人沮喪的簡單。 :-)我已經接受了你的答案,因爲我覺得它是最完整的。 – gordyr

1

的不確定性可能是在選擇,而不是在加入。連接看起來不錯。 $ aColumns可能包含沒有表名稱說明的「id」。

0
The LEFT JOIN keyword returns all rows from the left table (table_name1), 
even if there are no matches in the right table (table_name2). 

在你的情況下,table1和table2是相同的。因此,執行左連接可能沒有好處,因爲最終所有的行都會被返回。你可能想使用Inner Join。

相關問題