-- 查询
#查询emp表所有数据
select * from emp;
#查询所有员工姓名
select ename from emp;
#简单条件
select * from emp where empno = 7788;
#查询20号部门工资大于2000的员工信息
select * from emp where deptno = 20 and sal > 2000;
#查询工资在1500-2000之间的员工信息
select * from emp where sal >= 1500 and sal <= 2000;
select * from emp where sal BETWEEN 1500 AND 2000;
#查询工资大于2000,工资小于1000的员工信息
select * from emp where sal > 2000 or sal < 1000;
#查询员工编号为7788,7521,7369
#select * from emp where empno = 7788 or empno = 7521 or empno = 7369;
select * from emp where empno in(7788,7521,7369);
#查询所有的职位信息(去重)
select DISTINCT job from emp ;
#查询所有没有奖金的员工信息(对null判断 is [not] null)
select * from emp where comm = 0 or comm is not null;
#起别名(解释字段 简化字段) 字段|表 [as]别名
select empno 编号,ename 名称 from emp;
#查询姓名s开头的员工信息(模糊查询 like % :0到多个字符)
select * from emp where ename like 's%';
select * from emp where ename like '%t';
select * from emp where ename like '%s%';
select * from emp where ename like '_L%';
#查询前五条记录(分页) limit index,length
select * from emp limit 4,6;
#查询工资最高的五个人 ORDER BY 字段[asc | desc]
select * from emp order by sal desc limit 0,5;
#排序 (可以设置二级条件)
select * from emp order by sal desc ,empno desc;
#查询20号部门工资最高的三个员工
select * from emp where deptno = 20 ORDER BY sal LIMIT 0,3 ;
#查询30号部门名字包含s的员工信息
select * from emp where deptno = 30 and ename like '%s%';
#查询入职时间最短的员工信息
select * from emp ORDER BY hiredate desc LIMIT 0,1;
#查询入职时间超过35年
select * from emp where YEAR(now()) - year(hiredate) > 35;
#查询在当月月底前两天入职的信息
select * from emp where day(LAST_DAY(hiredate)) - 2 = day(hiredate);
select * from emp where hiredate=ADDDATE(LAST_DAY(hiredate), interval -2 day);
2.聚合函数(重点)
-- 聚合函数
#max() min() count() sum() avg()
select * from emp;
select max(sal) from emp;
select min(sal) from emp;
select count(*) from emp; #统计记录数
select count(1) from emp; #统计记录数
select count(comm) from emp; #统计字段数目,不会统计该字段为null的记录
select sum(sal) from emp;
select avg(sal) from emp;
3.分组函数(重点)
-- 分组函数 group
#注意:where 子句中不能写聚合函数
#where 子句执行顺序在group by 之前,语法也必须在group by 之前
#having 可以实现对分组之后的结果集再次进行检索。
#查询平均工资大于2000的部门编号和平均工资
select deptno,avg(sal) avg from emp group by deptno having avg> 2000;
#查询每个部门中工资大于1000的员工的平均工资
select deptno,avg(sal) from emp where sal > 1000 GROUP BY deptno;