subquery.md 1.2 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4
# 子查询

现有员工表

fix bug  
张志晨 已提交
5
```sql
M
Mars Liu 已提交
6 7 8 9 10 11 12 13 14 15 16
create table employee
(
    id     serial primary key,
    name   varchar(256),
    dept   varchar(256),
    salary decimal(12, 4)
);
```

Joe 希望找出比销售部(dept 为 sale)工资最高的员工工资更高的那部分人,查询出他们的完整信息,下面哪一项可以满足要求?

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
Mars Liu 已提交
24 25
## 答案

fix bug  
张志晨 已提交
26
```sql
M
Mars Liu 已提交
27 28 29 30 31 32 33 34 35 36 37
select id, name, dept, salary
from employee
where salary > (select max(salary)
                from employee
                where dept = 'sale')
```

## 选项

### A

fix bug  
张志晨 已提交
38
```sql
M
Mars Liu 已提交
39 40 41 42 43 44 45 46 47
select id, name, dept, salary
from employee
where dept = 'sale'
group by dept
having salary > max(salary)
```

### B

fix bug  
张志晨 已提交
48
```sql
M
Mars Liu 已提交
49 50 51 52 53 54 55 56 57
select l.id, l.name, l.dept, l.salary
from employee as l
         join employee as r on l.salary > max(r.salary)
where r.dept = 'sale'
group by r.dept 
```

### C

fix bug  
张志晨 已提交
58
```sql
M
Mars Liu 已提交
59 60 61 62 63 64 65
select id, name, dept, salary
from employee
having salary > (select max(salary) from employee where dept = 'sale')
```