题目
获取员工其当前的薪水比其manager当前薪水还高的相关信息,
第一列给出员工的emp_no,
第二列给出其manager的manager_no,
第三列给出该员工当前的薪水emp_salary,
第四列给该员工对应的manager当前的薪水manager_salary
第二列给出其manager的manager_no,
第三列给出该员工当前的薪水emp_salary,
第四列给该员工对应的manager当前的薪水manager_salary
数据内容
drop table if exists `dept_emp` ; drop table if exists `dept_manager` ; drop table if exists `salaries` ; 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 `dept_manager` ( `dept_no` char(4) NOT NULL, `emp_no` int(11) 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 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_manager VALUES('d001',10002,'1996-08-03','9999-01-01'); INSERT INTO salaries VALUES(10001,88958,'2002-06-22','9999-01-01'); INSERT INTO salaries VALUES(10002,72527,'1996-08-03','9999-01-01');
解题思路:
1. 建立员工工资表
2. 建立经理工作表
3. 关联以上俩个表
SELECT s1.emp_no, s2.emp_no AS manager_no, s1.salary AS emp_salary, s2.salary AS manager_salary FROM (SELECT de.emp_no, s.salary, de.dept_no FROM dept_emp AS de JOIN salaries AS s --员工工资表(用JOIN形式表达示例) ON de.emp_no = s.emp_no Where s.to_date = '9999-01-01' ) AS s1 LEFT JOIN (SELECT dm.emp_no, s.salary, dm.dept_no FROM dept_manager AS dm, salaries AS s WHERE dm.emp_no = s.emp_no --经理工资表(用WHERE形式表达示例) AND s.to_date = '9999-01-01' ) AS s2 ON s1.dept_no = s2.dept_no --关联2表 WHERE s1.salary > s2.salary --设定限定条件