查找并返回前职员,但不是当前职员

时间:2019-05-13 06:39:47

标签: mysql sql

给出下表:

Staff
+------------+--------+
| employeeID |  name  |
+------------+--------+
|     100100 | Kelly  |
|     101010 | John   |
|     222222 | Stuart |
+------------+--------+

Academics
+------------+----------+
| employeeID | degreeID |
+------------+----------+
|     100100 | PhD      |
|     101010 | Eng      |
|     222222 | Sci      |
+------------+----------+

Class
+------------+-----------+-----------+
| employeeID | studentID | subjectID |
+------------+-----------+-----------+
|     100100 |       998 | BUS_18_2  |
|     100100 |       921 | BUS_18_2  |
|     100100 |       901 | BUS_18_2  |
|     100100 |       934 | BUS_19_1  |
|     100100 |       964 | BUS_19_2  |
|     100100 |       934 | LED_19_1  |
|     100100 |       964 | LED_19_2  |
|     101010 |       901 | COE_19_2  |
|     101010 |       874 | COE_19_2  |
|     101010 |       823 | COE_19_2  |
|     222222 |       212 | FTR_17_2  |
|     222222 |       102 | FTR_17_1  |
|     222222 |       684 | FTR_18_1  |
+------------+-----------+-----------+

返回2019年未上课的所有员工的姓名和学位ID列表

我已经尝试过各种方法来构造嵌套的hading语句,以检测工作人员是否已经工作多年(基于对subjectID的计数),但是那或多或少都对其进行了“硬编码”,新条目可能会破坏这种方法(如示例所示。

预期结果

+------------+------------+
|    name    | degreecode |
+------------+------------+
|   stuart   | sci        |
+------------+------------+

2 个答案:

答案 0 :(得分:0)

使用关联的子查询与not exists

select distinct name, degreeid 
from staff a join academics b on a.employeeid=b.employeeid
join class c on a.employeeid=c.employeeid
where not exists 
   (select 1 from class c1 where c.employeeid=c1.employeeid and subjectID like '%_19%')

答案 1 :(得分:0)

基本思想是not exists。但是,您的数据模型似乎缺少有关2019年将提供的类的信息。假设class具有以下信息:

select s.name, a.degreeid 
from staff s join
     academics a
     on s.employeeid = a.employeeid
where not exists (select 1
                  from class c
                  where c.employeeid = s.employeeid and
                        c.year = 2019
                 );