2009-09-18 61 views
2

我有兩個mysql表,課程和student_courses,我需要從課程表中獲取唯一的course_names。但是當我嘗試執行我的查詢時遇到錯誤。嘗試使用DISTINCT和LEFT JOIN獲得唯一值時出現MySQL錯誤

繼承人我查詢

 SELECT 
      sc.c_id, 
      DISTINCT c.course_name 
     FROM 
      Courses AS c 
     LEFT JOIN Student_Courses AS sc ON c.c_id = sc.c_id 
     WHERE 
      sc.s_id = 4 

這是錯誤我得到

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT c.course_name 

FROM 課程爲C LEFT在3號線

回答

5

DISTINCT是一個關鍵字SELECT後立即使用(有一個看看Mysql SELECT syntax)。您無法區別選擇列,而是執行SELECT DISTINCT查詢。你可能想要的是GROUP BY。但你需要一個aggregate function(來告訴MySQL如何與其他列做 - 那些你不GROUP荷蘭國際集團BY)使用GROUP_CONCAT爲聚合函數(這只是串接各組用逗號所有列)例:

SELECT c.course_name, GROUP_CONCAT(sc.c_id), 
FROM Courses AS c 
LEFT JOIN Student_Courses AS sc ON c.c_id = sc.c_id 
WHERE sc.s_id = 4 
GROUP BY course_name 
2
SELECT 
     DISTINCT sc.c_id, 
     c.course_name 
FROM 
     Courses AS c 
LEFT JOIN Student_Courses AS sc ON c.c_id = sc.c_id 
WHERE 
     sc.s_id = 4 

的DISTINCT JOIN Student_Courses AS「關鍵字必須是選擇後的第一個單詞,因爲它會適用於整行。
這是因爲如果你說:

SELECT DISTINCT(sc.c_id, c.course_name, ...) FROM ... 

你不能說:

SELECT sc.c_id, DISTINCT(c.course_name, ...) FROM ...