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`)); 查找最晚入职员工的所有信息 select * from employees where hire_date=(select max(hire_date) from employees) 查找入职员工时间排名倒数第五的员工所有信息 SELECT * FROM employees where hire_date=(select distinct hire_date from employees order by hire_date desc limit 4,1)
多表查询: 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`)); 查找各个部门当前(to_date='9999-01-01')领导当前薪水详情以及其对应部门编号dept_no select s.* ,d.dept_no from salaries as s join dept_manager as d on s.emp_no=d.emp_no where s.to_date = '9999-01-01' and d.to_date='9999-01-01'; SELECT s.*, d.dept_no FROM salaries s , dept_manager d WHERE s.to_date='9999-01-01' AND d.to_date='9999-01-01' AND s.emp_no = d.emp_no;
查找所有已经分配部门的员工的last_name和first_name,以及对应部门编号dept_no 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 `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`)); select e.last_name,e.first_name,d.dept_no from employees as e inner join dept_emp as d where e.emp_no=d.emp_no INNER JOIN 两边表同时有对应的数据,即任何一边缺失数据就不显示。 LEFT JOIN 会读取左边数据表的全部数据,即便右边表无对应数据。 RIGHT JOIN 会读取右边数据表的全部数据,即便左边表无对应数据。
查找所有员工的last_name和first_name以及对应部门编号dept_no,也包括展示没有分配具体部门的员工 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 `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`)); SELECT ep.last_name, ep.first_name, dp.dept_no FROM employees ep LEFT JOIN dept_emp dp ON ep.emp_no = dp.emp_no
查找所有员工入职时候的薪水情况,给出emp_no以及salary, 并按照emp_no进行逆序 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`)); select e.emp_no, s.salary from salaries as s inner join employees as e on e.emp_no=s.emp_no and e.hire_date=s.from_date order by e.emp_no desc