【良心正确答案】
/* 其实这种题目有时需求不明确,官方给的数据也不太好验证答案,故可以自己修改或增加数据进行验证 */
/* 我的数据库是mysql8.0 */
创建表和插入数据:
CREATE TABLE dept_emp
(emp_no
int(11) NOT NULL,dept_no
char(4) NOT NULL,from_date
date NOT NULL,to_date
date NOT NULL,
PRIMARY KEY (emp_no
,dept_no
));
CREATE TABLE salaries
(emp_no
int(11) NOT NULL,salary
int(11) NOT NULL,from_date
date NOT NULL,to_date
date NOT NULL,
PRIMARY KEY (emp_no
,from_date
));
INSERT INTO salaries
VALUES (10001, 90000, '1986-06-26', '1987-06-26');
INSERT INTO salaries
VALUES (10001, 95000, '2002-06-22', '9999-01-01');
INSERT INTO salaries
VALUES (10002, 72527, '1996-08-03', '1997-08-03');
INSERT INTO salaries
VALUES (10002, 72527, '2000-08-02', '2001-08-02');
INSERT INTO salaries
VALUES (10002, 95000, '2001-08-02', '9999-01-01');
INSERT INTO salaries
VALUES (10003, 90000, '1996-08-03', '1997-08-03');
INSERT INTO salaries
VALUES (10004, 80000, '1996-01-01', '1996-03-01');
INSERT INTO salaries
VALUES (10004, 89000, '1996-08-08', '9999-01-01');
INSERT INTO dept_emp
VALUES (10001, 'd001', '1986-06-26', '9999-01-01');
INSERT INTO dept_emp
VALUES (10002, 'd001', '1996-08-03', '9999-01-01');
INSERT INTO dept_emp
VALUES (10003, 'd001', '1996-08-03', '1997-08-03');
INSERT INTO dept_emp
VALUES (10004, 'd002', '1996-08-08', '9999-01-01');
OK,到这里可以分析一下题目了,考虑周全一点(有多个部门且同个部门有相同最高薪水),分为2种需求。
1、查询各个部门的最高薪水的员工信息
2、查询所有部门中最高薪水的员工信息
3、若不用emp_no,只要dept_no,salary,这个就简单了,分组即可。(其实不想说的,算了,后面直接给代码吧,不解析了)
【需求1】
sql代码:
select de.dept_no, emp_no, max_salary
FROM dept_emp de
join
(
select dept_no, max(salary) as max_salary FROM salaries s join dept_emp de on s.emp_no = de.emp_no where s.to_date = '9999-01-01' and de.to_date = '9999-01-01' group by dept_no
) t on de.dept_no = t.dept_no
where de.to_date = '9999-01-01'
解析:
(1)表t得到各个部门最高薪水
(2)连接dept_emp表,获取emp_no即可。(这样就可以把同部门最高的薪水的多个员工都列出来了)
【需求2】
sql代码:
select *
FROM salaries
where salary =
(
select max(max_salary) from ( select dept_no, max(salary) as max_salary FROM salaries s join dept_emp de on s.emp_no = de.emp_no where s.to_date = '9999-01-01' and de.to_date = '9999-01-01' group by dept_no )t
)
解析:
(1)表t得到各个部门最高薪水
(2)然后再取最高薪水,即所有部门中最高薪水(跟需求1相比,也就多了这一步)
(3)最后连接dept_emp表,获取emp_no即可。(这样就可以把同部门最高的薪水的多个员工都列出来了)
【需求3】
sql代码:
select dept_no, max(salary)
from dept_emp as de
join salaries as s
on de.emp_no = s.emp_no
and de.to_date='9999-01-01'
and s.to_date='9999-01-01'
group by dept_no
试试吧,有用请良心点赞,顶上去!!!