exists.md 1.3 KB
Newer Older
M
in  
Mars Liu 已提交
1 2 3 4
# Exists

Joe 想从员工表

fix bug  
张志晨 已提交
5
```sql
M
in  
Mars Liu 已提交
6 7
create table employee(
    id int primary key auto_increment,
M
Mars Liu 已提交
8
    dept_id int,
M
in  
Mars Liu 已提交
9 10 11 12 13 14 15 16
    name varchar(256),
    post varchar(16)
)
```

中找出所有其所在部门没有助理(post 为 `assistant`)的员工信息。由于 Joe 没有其它表的查询权限,
他只能查询员工表,并且这一次他想用 exists 实现。这个查询应该是:

M
Mars Liu 已提交
17 18
<hr/>

F
feilong 已提交
19
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill){target="_blank"}。
F
feilong 已提交
20

F
feilong 已提交
21 22
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
23

M
in  
Mars Liu 已提交
24 25
## 答案

fix bug  
张志晨 已提交
26
```sql
L
luxin 已提交
27
select id, name, dept
M
in  
Mars Liu 已提交
28
from employee as o
29 30 31 32
where not exists(
    select * 
    from employee as i 
    where o.dept = i.dept and post='assistant'); 
M
in  
Mars Liu 已提交
33 34 35 36 37 38
```

## 选项

### A

fix bug  
张志晨 已提交
39
```sql
M
in  
Mars Liu 已提交
40 41
select id, name, dept
from employee as o
42 43 44 45
where exists(
    select * 
    from employee as i 
    where o.dept = i.dept and post='assistant'); 
M
in  
Mars Liu 已提交
46 47 48
```

### B
fix bug  
张志晨 已提交
49
```sql
M
in  
Mars Liu 已提交
50 51
select id, name, dept 
from employee as o
52 53 54
where 'assistant' != exists(
    select post 
    from employee as i); 
M
in  
Mars Liu 已提交
55 56
```

L
luxin 已提交
57
### C
M
in  
Mars Liu 已提交
58

fix bug  
张志晨 已提交
59
```sql
M
in  
Mars Liu 已提交
60 61
select id, name, dept 
from employee as o
62 63 64 65
where 'assistant' = not exists(
    select post 
    from employee as i 
    where o.dept = i.dept); 
M
in  
Mars Liu 已提交
66
```