2013-08-19 85 views
1

我是新來的MySQL所以請告訴我,如果我的問題是缺少信息,ERROR 1052(23000):在where子句是不明確的列「COURSE_ID」

我有工作正常的查詢:

select au.email, sm.created, sm.grade, sm.max_grade 
from auth_user au, courseware_studentmodule sm 
where sm.student_id = au.id 
and course_id = 'MyCourse' 
and sm.module_type = 'problem'; 

但是,當我想從一個不同的表中添加另一列:

select au.email, sm.created, sce.created , sm.grade, sm.max_grade 
from auth_user au, courseware_studentmodule sm, student_courseenrollment sce 
where sm.student_id = au.id and sm.student_id = sce.id 
and course_id = 'MyCourse' 
and sm.module_type = 'problem'; 

我得到這個錯誤

ERROR 1052 (23000): Column 'course_id' in where clause is ambiguous 

任何人都知道爲什麼?

感謝

+0

可能重複:// stackoverflow.com/questions/17029096/how-to-fix-an-ambigous-column-name-error-using-inner-join-error) – Ben

回答

4

這是因爲列course_id存在於兩個以上的表中。

寫sm.course_id或sce.course_id它會起作用。

+0

非常感謝,問題:因爲course_id只存在於sm中,第一個查詢如何工作[當我只有兩張桌子時]? – user2333346

+0

我相信它只在sm – user2333346

+0

即使你確定,錯誤信息證明你忽略了一些東西...... –

2

要加入多個表,至少兩個表都列course_id。在您的聲明and course_id = 'MyCourse'中,您沒有指定哪個表具有course_id。

+0

我確實檢查過,實際上只有courseware_studentmodule sm 有course_id列,我將上面的內容切換到sm.course_id ='MyCourse' 我剛剛得到同樣的錯誤,我知道它的第一個工作原理很奇怪! – user2333346

2

student_courseenrollment和您的其他表中的一個都有一個名爲course_id的列。使用表別名,例如au.course_id

2

時,您需要使用表的別名與課程ID的列其

sce.course_id

如下面這個評論指出可能會改變你的結果,以便使用該表的表名用於where子句或該表的別名

+1

這幾乎肯定是不正確的;在添加該表之前,WHERE子句中的限制是在那裏。由於它不是JOIN的一部分,你可能會改變結果。 – Ben

+0

但是,如果您僅查看au和sm上的第一個查詢,則course_id列僅存在於sm中,但他的查詢正常工作! – user2333346

0

您正在使用兩個具有相同列名的不同表。如果你想在任何查詢中使用的列名,你應符合表名,例如使用:

select * from table1,table2 where table1.userId='any id'; 
的(HTTP [如何「使用內部連接ambigous列名錯誤」錯誤修復的]
相關問題