salary.md 1.3 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4
# 工资最高的人

现有员工信息表如下:

M
Mars Liu 已提交
5
```mysql
M
Mars Liu 已提交
6 7 8
create table employee
(
    id     serial primary key,
M
Mars Liu 已提交
9 10
    name   varchar(256),
    dept   varchar(256),
M
Mars Liu 已提交
11 12 13 14 15 16
    salary money
);
```

下面哪条查询,可以给出每个部门工资最高的员工的 id, name, dept, salary 四项信息?

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

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

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

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

M
Mars Liu 已提交
26
```mysql
M
Mars Liu 已提交
27 28 29 30 31 32 33 34 35 36 37 38
select l.id, l.name, l.dept, l.salary
from employee as l
         join (select max(salary) as salary, dept
               from employee
               group by dept) as r
              on l.dept = r.dept and l.salary = r.salary
```

## 选项

### select 与 group by 不匹配

M
Mars Liu 已提交
39
```mysql
M
Mars Liu 已提交
40 41 42 43 44 45 46
select id, name, dept, max(salary)
from employee
group by dept;
```

### group by 不对

M
Mars Liu 已提交
47
```mysql
M
Mars Liu 已提交
48 49 50 51 52 53 54
select id, name, dept, max(salary)
from employee
group by dept, id, name;
```

### group by 不对

M
Mars Liu 已提交
55
```mysql
M
Mars Liu 已提交
56 57 58 59 60 61 62 63
select id, name, dept, max(salary)
from employee
group by dept, id, name
having salary = max(salary);
```

### 结构错误

M
Mars Liu 已提交
64
```mysql
M
Mars Liu 已提交
65 66 67 68 69 70
select id, name, dept, max(salary)
from employee
where salary = max(salary)
group by dept;
```