SQL1 查找最晚入职员工的所有信息
语句
#方法一
select * from employees where hire_date=(select MAX(hire_date) from employees) limit 1
#方法二
select * from employees order by hire_date desc limit 1
知识点
- order by 排序
- desc
- desc (descend)降序排列数据:select * from 表 order by 字段 desc; select * from employees order by hire_date desc ; (asc是升序关键字)
- limit
- 在select语句中使用limit子句来约束结果集中的行数。limit子句接受一个或两个参数
- limit offset,count—offset为跳过的数量,count为要取得数量
- 获取前2行数据
- select * from employees limit 2 ; select * from employees limit 0,2
SQL2 查找入职员工时间排名倒数第三的员工所有信息
语句
select * from employees where hire_date=(select distinct hire_date from employees order by hire_date desc limit 1 offset 2)
# 跳过倒数第一名和第三名取第三名
知识点
- distinct关键字用于返回唯一不同的值
- select distinct 字段 from 表名
- select distinct hire_date from employees 去掉相同的hire_date
SQL3 查找当前薪水详情以及部门编号dept_no
语句
select S.*,D.dept_no from salaries S inner join dept_manager D on S.emp_no=D.emp_no
知识点
-
连接查询
- 内连接查询
- 内连接查询可以查询两张或两张以上的表,从左表中取出每一条记录,去右表中与所有的记录进行匹配:匹配必须是某一条件在左表中与右表中相同最终才能保留结果,否则不保留
- from 左表[inner] join 右表 on 左表.字段=右表.字段
- 外连接查询
- 以某张表为主,取出里面的所有记录,然后每条与另外一张表进行连接:不管能不能匹配上条件,最终都能保留:能匹配,正确保留;不能匹配,其他表的字段设为NULL
- 右连接
- 以右表为主 from 左表 right join右表 on 左表.字段=右表.字段
- 右表不管能不能匹配上条件,最终都会保留:能匹配,正确的保留; 若不能匹配,左表的字段都置NULL
- 左连接
- 以左表为主表 from 左表 left join 右表 on 左表.字段 = 右表.字段;
- 左表不管能不能匹配上条件,最终都会保留:能匹配,正确的保留; 若不能匹配,右表的字段都置NULL
- 内连接查询
-
联合查询
- union:连接两个以上的select语句的结果组合到一个结果集合中。多个select语句会删除重复的数据
- union all: 用于将不同表中相同列表中查询的数据展示出来(包含重复数据)
- MySQL UNION 操作符 | 菜鸟教程 (runoob.com)
-
子查询
select * from student where score in (select score from student where score>80);
SQL4 查找所有已经分配部门的员工的last_name和first_name以及dept_no
语句
select E.last_name,E.first_name,D.dept_no from employees E inner join dept_emp D on E.emp_no=D.emp_no
SQL5 查找所有员工的last_name和first_name以及对应部门编号dept_no
语句
select E.last_name,E.first_name,D.dept_no from employees E left join dept_emp D on E.emp_no=D.emp_no
SQL6 查找薪水记录超过15条的员工号emp_no以及其对应的记录次数t
语句
select emp_no,count(emp_no) as t from salaries group by emp_no having t>15
知识点
- group by
- 用来结合聚合函数,根据一个或多个列对结果集进行分组
- having
- 在SQL中增加having子句的原因是,where无法与合计函数一起使用