嗨,我正在学习MySQL课程,我坚持一个问题,这是我的表
Student(S_ID, S_FIRST_NAME, S_LAST_NAME, S_MAJOR)
Course(C_ID, C_NAME, C_INST_NAME, C_ROOM)
takes(S_ID,C_ID)
我的问题是,如何查找至少需要两名学生的姓名 课程由彼得森教授,但只参加戴维森的一门课程。
我能够得到至少参加2门课程的学生的成绩 彼得森有以下查询:
select student.S_FIRST_NAME from student inner join
student_course on student_course.S_ID = student.S_ID
-> inner join course on course.C_ID = student_course.C_ID
-> where course.C_INST_NAME = 'Peterson'
-> group by student.S_FIRST_NAME
-> having count(distinct course.C_ID)>=2;
+--------------+
| S_FIRST_NAME |
+--------------+
| Eden |
| Kery |
| Micheal |
| Yeison |
+--------------+
我尝试了以下查询以满足这两个要求:
select student.S_FIRST_NAME from student inner join student_course on
student_course.S_ID = student.S_ID inner join course on course.C_ID =
student_course.C_ID where course.C_INST_NAME = 'Peterson' group by
student.S_FIRST_NAME having count(distinct course.C_ID)>=2 and
student.S_FIRST_NAME from student inner join student_course on
student_course.S_ID = student.S_ID inner join course on course.C_ID =
student_course.C_ID where course.C_INST_NAME = 'Davidson' group by
student.S_FIRST_NAME having count(distinct course.C_ID)=1;
但没有工作得到这个错误:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MariaDB server version for the right syntax to use
near 'from student
inner join student_course on student_course.S_ID = student.S_ID
in' at line 1
I went back and look at the code again but couldn't figure it out what the
problem is, and inner join is the complicated one i think it is just for me.
any help would be appreciated please !! thank you in advance.
答案 0 :(得分:1)
这个答案的基本策略是由学生在Course
表格上进行汇总,并且只保留那些在彼得森至少有两门课程且在戴维森最多有一门课程的学生。
SELECT s.S_FIRST_NAME,
s.S_LAST_NAME
FROM Student s
INNER JOIN
(
SELECT t.S_ID
FROM takes t
INNER JOIN Course c
ON t.C_ID = c.C_ID
GROUP BY t.S_ID
HAVING SUM(CASE WHEN c.C_INST_NAME = 'Peterson' THEN 1 ELSE 0 END) >= 2 AND
SUM(CASE WHEN c.C_INST_NAME = 'Davidson' THEN 1 ELSE 0 END) <= 1
) t
ON s.S_ID = t.S_ID