簡體   English   中英

SQL 子查詢未返回預期結果

[英]SQL sub-queries not returning expected result

Select name 
from instructor 
where dept_name = 'Comp. Sci.' and ID in
    (select ID
     from course 
     where title != 'Intro. to Computer Science')

有了這個輸入,我希望輸出是從未教過“計算機科學導論”的教師,但輸出是來自 CS 的所有教師,而不僅僅是沒有教過計算機科學導論的 1 位教授 Brant。我做錯了什么?

講師

課程

教

這應該適合你

select i.name 
from instructor as i, teaches as t
where i.dept_name = 'Comp. Sci.' and i.ID=t.ID
and not exists (
  select 1 
  from course 
  where t.ID = course.course_id and title = 'Intro. to Computer Science'
)

使用不存在:

select i.name 
from instructor i
where i.dept_name = 'Comp. Sci.' 
and not exists (
  select 1 
  from teaches t inner join course c
  on c.course_id = t.course_id 
  where t.id = i.id and c.title = 'Intro. to Computer Science'
)

或按教師分組並在HAVING子句中設置條件:

select i.name 
from instructor i
inner join teaches t on t.id = i.id
inner join course c on c.course_id = t.course_id 
where i.dept_name = 'Comp. Sci.'
group by i.id, i.name
having count(case when c.title = 'Intro. to Computer Science' then 1 end) = 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM