混淆多行子查询比较

问题描述 投票:0回答:4

我现在正在Oracle SQL Developer中工作,并且对查询感到困惑。提示内容如下: 提供从未教过课程部分的教师的字母列表。列出称呼,名字,姓氏和邮政编码。

这是我目前的尝试:

SELECT i.Salutation, i.First_Name, i.Last_Name, i.Zip
FROM Instructor i
  JOIN Section s 
    ON i.Instructor_Id = s.Instructor_Id
WHERE 0 in (SELECT COUNT(Instructor_Id)
FROM Section 
GROUP BY Instructor_Id) 

当我搜索实际拥有类的教师时,我的代码可以工作(返回教师的所需输出),但是当我搜索没有类的教师时,它无法识别。我不太确定如何解决这个问题,任何帮助表示赞赏。

sql oracle subquery
4个回答
1
投票

您可以使用NOT EXISTS来获取不在Section表中的教师。

SELECT 
  Salutation,
  First_Name,
  Last_Name,
  Zip
FROM Instructor i
WHERE NOT EXISTS (
 SELECT
  *
 FROM Section s
 WHERE i.Instructor_Id = s.Instructor_Id)
ORDER BY Last_Name

1
投票

默认连接是INNER,这意味着只返回教师ID匹配的节中的行。您可能想要指定LEFT OUTER JOIN [1]。另一个常见的构造是使用WHERE NOT EXISTS [2]

[1] What is the difference between "INNER JOIN" and "OUTER JOIN"?

[2] NOT IN vs NOT EXISTS


1
投票

以下是从未教过任何课程的教师。将'HAVING'条款条件更改为> 0,以获得教授某些课程的教师:

SELECT 
  i.Salutation,
  i.First_Name,
  i.Last_Name,
  i.Zip 
FROM Instructor i
left join section s
on i.instructor_id = s.instructor_id
group by 
i.instructor_id,
i.Salutation,
  i.First_Name,
  i.Last_Name,
  i.Zip  
having count(s.section_id)  = 0 /* > 0 if looking for instructors who have taught some courses */
order by i.last_name, i.first_name

1
投票

从已教授的教师的Section表中获取ID列表。使用NOT IN查看谁没有教过任何课程。

SELECT i.Salutation, i.First_Name, i.Last_Name, i.Zip
FROM Instructor i
WHERE i.Instructor_Id NOT IN (
    SELECT DISTINCT s.Instructor_Id
    FROM Section
)
© www.soinside.com 2019 - 2024. All rights reserved.