【问题标题】:Query with exists and not exists查询存在和不存在
【发布时间】:2020-06-14 23:18:15
【问题描述】:

我有一个包含 5 个表的数据库。

COURSES (***CourseID***, CourseName, Credit)

TEACHERS (***SSN***, Name)

OFFER (***CourseID***, ***SSN***)

STUDENTS (***StudentID***, Name, Department)

ENROLL (***StudentID***, ***CourseID***, Semester)

我想查找至少注册了一名“汽车工程”学生的课程名称。但也不能由“天使”提供该课程。我的意思是至少招收一名“汽车工程”学生且不是由“天使”提供(教授)的课程。

我从另一个问题得到了以下答案,但我不知道如何从这里开始。

select C.CourseName
from Courses C
-- A student from the selected department is enrolled in this course
where exists (
    select 1
    from Enroll E
    inner join Students S on S.StudentId = E.StudentId
    where S.Department = 'Automotive Engineering' and E.CourseID = C.CourseID
)

以上代码为我提供了至少一名“汽车工程”学生注册的课程名称,但我如何检查该课程不是由“天使”提供?

【问题讨论】:

  • 请不要做你刚刚尝试做的事情,这会删除整个问题。这不是这个网站的工作方式。问题一直存在,答案也会一直存在,以帮助其他人。
  • 如果您有新问题,请发布新问题。不要以使合理答案无效的方式更改问题。

标签: sql sql-server join select subquery


【解决方案1】:

exists 方法可以过滤至少一名相关学生参与的课程。从您现有的查询开始,您可以添加更多的连接以带上课程老师并过滤掉'Angel'

select C.CourseName
from Courses C
inner join Offer O on O.CourseId = C.CourseID
inner join Teachers T on T.SSN = O.SSN
where 
    exists (
        select 1
        from Enroll E
        inner join Students S on S.StudentId = E.StudentId
        where S.Department = 'Automotive Engineering' and E.CourseID = C.CourseID
    )
    and T.Name <> 'Angel'

【讨论】:

    猜你喜欢
    • 2011-02-16
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    相关资源
    最近更新 更多