subquery.md 968 字节
Newer Older
M
Mars Liu 已提交
1 2 3 4 5
# 子查询

现有员工表

```postgresql
M
format  
Mars Liu 已提交
6 7 8 9 10
create table employee
(
    id     serial primary key,
    name   text,
    dept   text,
M
Mars Liu 已提交
11 12 13 14 15 16 17 18 19
    salary money
)
```

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

## 答案

```postgresql
M
format  
Mars Liu 已提交
20
select id, name, dept, salary
M
Mars Liu 已提交
21
from employee
M
format  
Mars Liu 已提交
22 23 24
where salary > (select max(salary)
                from employee
                where dept = 'sale')
M
Mars Liu 已提交
25 26 27 28 29 30 31
```

## 选项

### A

```postgresql
M
format  
Mars Liu 已提交
32
select id, name, dept, salary
M
Mars Liu 已提交
33 34
from employee
where dept = 'sale'
M
format  
Mars Liu 已提交
35 36
group by dept
having salary > max(salary)
M
Mars Liu 已提交
37 38 39 40 41
```

### B

```postgresql
M
format  
Mars Liu 已提交
42 43 44 45
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'
M
Mars Liu 已提交
46 47 48 49 50 51
group by r.dept 
```

### C

```postgresql
M
format  
Mars Liu 已提交
52
select id, name, dept, salary
M
Mars Liu 已提交
53
from employee
M
format  
Mars Liu 已提交
54
having salary > (select max(salary) from employee where dept = 'sale')
M
Mars Liu 已提交
55 56 57 58
```