0
select firstName, lastName from students, courses, registration
where students.studentID = registration.studentID 
and courses.courseCode = registration.courseCode 
and gender = 'M' and courseName = 'Database Systems' 
in(select firstName, lastName 
from students, courses, registration
where students.studentID = registration.studentID 
and courses.courseCode = registration.courseCode 
and gender = 'M' and courseName = 'C++');``

我需要找到同时学习过数据库系统和 C++ 的男学生,为此我需要加入学生、注册和课程表,

4

3 回答 3

0

由于您使用in运算符的方式,您的查询失败,这需要左侧的列名或表达式。

根据您对目标的描述,我怀疑您的查询可以重写为使用exists具有相关子查询的条件进行过滤,如下所示:

select 
    firstName, 
    lastName 
from students s
where 
    gender = 'M'
    and exists(
        select 1
        from courses c
        inner join registration r on c.courseCode = r.courseCode 
        where 
            c.courseName = 'Database Systems' 
            and s.studentID = r.studentID 
    )
    and exists(
        select 1
        from courses c
        inner join registration r on c.courseCode = r.courseCode 
        where 
            c.courseName = 'C++' 
            and s.studentID = r.studentID 
    )   

另一种可能的解决方案是使用聚合,并带有一个having用于过滤的子句:

select s.firstName, s.lastName 
from students s
inner join registration r 
    on s.studentID = r.studentID 
inner join courses c 
    on  c.courseCode = r.courseCode 
    and c.courseName in ('Database Systems',  'C++' )
where s.gender = 'M'
group by s.studentID, s.firstName, s.lastName 
having count(distinct c.courseName) = 2
于 2019-11-09T22:11:34.223 回答
0

您的 in 子句缺少一些列尝试

select 
   firstName, lastName 
from students, courses, registration
where students.studentID = registration.studentID 
and courses.courseCode = registration.courseCode 
and gender = 'M' and courseName = 'Database Systems' 
and students.studentID
in (select studentID 
from students, courses, registration
where students.studentID = registration.studentID 
and courses.courseCode = registration.courseCode 
and gender = 'M' and courseName = 'C++');
于 2019-11-09T22:11:57.957 回答
0

使用子句可以更轻松地编写此查询,HAVING以检查学生从集合('Database Systems','C++')中选择的课程计数是否为 2:

SELECT s.studentID, s.firstName, s.lastName 
FROM students s
JOIN registration r ON s.studentID = r.studentID 
JOIN courses c ON c.courseCode = r.courseCode 
WHERE s.gender = 'M' AND c.courseName IN ('Database Systems', 'C++')
GROUP BY s.studentID, s.firstName, s.lastName
HAVING COUNT(DISTINCT c.courseName) = 2

请注意,我已JOIN根据条件以首选样式重写了您的 s ON

于 2019-11-09T22:15:58.430 回答