题目描述
查找最晚入职员工的所有信息
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`));
输入描述:
无
输出描述:
emp_no | birth_date | first_name | last_name | gender | hire_date |
---|---|---|---|---|---|
10008 | 1958-02-19 | Saniya | Kalloufi | M | 1994-09-15 |
好了题目出来了,先建表
然后,插入如下测试代码
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'); ```
然后这道题说的是最晚员工,也就是说hire_date字段的最大值,如何比较max的最大值呢?
我们可以用到max()这个函数,所以我的答案是
select * from employees where hire_date=(select max(hire_date) from employees)`
执行,结果正确
但是,我学弟说,他用limit也能得到正确的结果,代码如下
select emp_no,birth_date,first_name,last_name,gender,hire_date from employees where hire_date = (select hire_date from employees order by hire_date limit 1);```
这样确实是可以的,但是如果我们多插入一行数据
INSERT INTO employees VALUES(10013,'1958-02-19','kang','shifu','M','1994-09-15'); `
这样的话,虽然kanshifu和saniya 都是最晚入职,但是只能选择一个,所以这样的话并不是很可取,所以保险的话,用我的方法