salary.md 1.0 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 17 18
    salary money
);
```

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

## 答案

M
Mars Liu 已提交
19
```mysql
M
Mars Liu 已提交
20 21 22 23 24 25 26 27 28 29 30 31
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 已提交
32
```mysql
M
Mars Liu 已提交
33 34 35 36 37 38 39
select id, name, dept, max(salary)
from employee
group by dept;
```

### group by 不对

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

### group by 不对

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

### 结构错误

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