例:查找当前薪水(to_date=‘9999-01-01‘)排名第二多的员工编号emp_no、薪水salary、last_name以及first_name,不准使用order by
CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,
PRIMARY KEY (`emp_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`));
解答思路:
此题方法较多
方法一:
利用两次MAX,连同select嵌套
SELECT e.emp_no, MAX(s.salary) AS salary, e.last_name, e.first_name
FROM employees AS e INNER JOIN salaries AS s
ON e.emp_no = s.emp_no
WHERE s.to_date =
‘9999-01-01‘
AND s.salary NOT IN (SELECT MAX(salary) FROM salaries WHERE to_date =
‘9999-01-01‘
)
方法二:
利用max选出最大,用where 限定小于最大值的,然后再取最大的那个
select a.emp_no,max(b.salary),a.last_name,a.first_name
from employees a inner join salaries b
on a.emp_no=b.emp_no
where b.salary<(select max(salary) from salaries)
and b.to_date = ‘9999-01-01‘