我有两个mysql表,课程和student_courses,我需要从课程表中获取唯一的course_names。但是在尝试执行查询时我得到了一个错误。
继承我的查询
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
这 课程AS c LEFT JOIN Student_Courses AS'在第3行
答案 0 :(得分:6)
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
答案 1 :(得分: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关键字必须是select之后的第一个单词,因为它将应用于整行 就好像你说:
SELECT DISTINCT(sc.c_id, c.course_name, ...) FROM ...
你不能说:
SELECT sc.c_id, DISTINCT(c.course_name, ...) FROM ...