有一个员工employees表简况如下:
请你查找employees里最晚入职员工的所有信息,以上例子输出如下:
drop table if exists `employees` ; 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`)); INSERT INTO employees VALUES(10001,'1953-09-02','Georgi','Facello','M','1986-06-26'); INSERT INTO employees VALUES(10002,'1964-06-02','Bezalel','Simmel','F','1985-11-21'); INSERT INTO employees VALUES(10003,'1959-12-03','Parto','Bamford','M','1986-08-28'); INSERT INTO employees VALUES(10004,'1954-05-01','Chirstian','Koblick','M','1986-12-01'); INSERT INTO employees VALUES(10005,'1955-01-21','Kyoichi','Maliniak','M','1989-09-12'); INSERT INTO employees VALUES(10006,'1953-04-20','Anneke','Preusig','F','1989-06-02'); INSERT INTO employees VALUES(10007,'1957-05-23','Tzvetan','Zielinski','F','1989-02-10'); INSERT INTO employees VALUES(10008,'1958-02-19','Saniya','Kalloufi','M','1994-09-15'); INSERT INTO employees VALUES(10009,'1952-04-19','Sumant','Peac','F','1985-02-18'); INSERT INTO employees VALUES(10010,'1963-06-01','Duangkaew','Piveteau','F','1989-08-24'); INSERT INTO employees VALUES(10011,'1953-11-07','Mary','Sluis','F','1990-01-22');
10008|1958-02-19|Saniya|Kalloufi|M|1994-09-15
-- 如果最晚只有一个人或只需要选一个最晚的 select * from employees order by hire_date desc limit 1 -- 如果最晚有多个人或者为了适应更多情况 select * from employees where hire_date = ( select max(hire_date) from employees )
【场景】:查找最大值的所有信息
【分类】:in子查询
难点:
1.考虑到最晚入职的员工不止一名的情况。
员工表中的入职时间是只记录到天没有精确到秒,会有可能出现最晚入职的员工不止一名的情况。所以这也在启发我们建表的时候最好考虑到这种情况,把入职时间精确到秒。
如果有多名员工最晚入职如何查找
分两步走,一、先找到入职最晚(最大)日期;二、再根据日期筛选员工信息。
in
、= 子查询 前往查看:MySQL 嵌套子查询 with子句 from子查询 in子查询 join子查询
对入职日期倒排序,取第一条数据。
#错误解法 select * from employees order by hire_date desc limit 1
方法一:
in 子查询
select emp_no, birth_date, first_name, last_name, gender, hire_date from employees where hire_date in ( select max(hire_date) as max_date from employees)
方法二:
= 子查询
select emp_no, birth_date, first_name, last_name, gender, hire_date from employees where hire_date = ( select max(hire_date) as max_date from employees)
SELECT * FROM employees WHERE hire_date = ( SELECT MAX(hire_date) FROM employees )
SELECT * FROM employees ORDER BY hire_date DESC LIMIT 0,1