一、单表数据查询
1)查询整张表中所有字段
select * from emp;
运行结果:
2)查询一个表中部分字段
select empno, ename,sal,job from emp;
运行结果:
3)查询表中字段时使用算术表达式
select empno, ename,sal,sal*1.08 from emp;
select empno, ename,sal, sal*12 from emp;
select empno, ename,sal, sal*12 +1000 from emp;
注:在Select语句中,对数值型数据可以使用算术运算符创建表达式
运行结果:
4)查询时使用字段别名
select empno as 员工编号, ename 员工姓名, sal*12 年薪 from emp;
select empno, ename "Ename", sal*12 "Anual Salary" from emp;
select sal*12+5000 as "年度工资(加年终奖)" from emp;
运行结果:
注:
别名如果含有空格或其他特殊字符或大小写敏感,需用双引号引起来。
AS可以省略
二、去重查询
缺省情况下,查询结果中包含所有符合条件的记录行,包括重复行
如:
select deptno from emp;
运行结果:
使用DISTINCT关键字可从查询结果中清除重复行
如:
select distinct deptno from emp;
运行结果:
三、排序查询
使用order by 子句对查询结果进行排序
排序方式包括升序(asc,缺省)和降序(desc)两种:
select empno, ename, sal from emp order by sal;
select empno, ename, sal from emp order by sal desc ;
运行结果:
按多字段排序:
select deptno, empno, ename, sal from emp order by deptno, sal;
使用字段别名排序:
select empno, ename, sal*12 annsal from emp order by annsal;
四、分页查询
1)查询前三条客户信息
select * from emp limit 3
运行结果:
2)查询从第三条往下数的共6条信息
select * from emp limit 3,6
运行结果:
五、合并查询
作用:将多个select语句联合(合并)为一个select语句
关键字:
1)union all :不管是否重复,全部合并
2)union: 如果有重复的,过滤掉重复的
六、where子句
select * from emp where deptno=10;
select * from emp where ename = 'JACK';
select * from emp where hiredate = '2020-12-12';
注意:
字符串和日期值要用单引号扩起来
字符串大小写敏感
日期值格式敏感,缺省的日期格式是'YYYY-MM-DD HH:mm:ss'
不等于:<>
select * from emp where deptno <> 30;
介于二者之间:between...and...
select * from emp where sal between 1600 and 2900;
出现在集合中:in
select * from emp where ename in('SMITH','CLARK','KING');
模糊查询:like
%:通配符 _:表示一个字符
select * from emp where ename like '_S%'; --第二个字符是S的
非空判断:is null
select * from emp where comm is not null;
运算符优先级:算术>连接>比较>逻辑
select * from emp where job='SALESMAN' or job='CLERK' and sal>=1280;
select * from emp where (job='SALESMAN' or job='CLERK') and sal>=1280;
--使用小括号强行改变优先级
七、group by子句
作用:GROUP BY 子句将表中数据分成若干小组
select deptno, avg(sal) from emp group by deptno;
select deptno, count(*),avg(sal) from emp group by deptno;
注意事项:
1、出现在select列表中的字段,如果不是包含在多行函数中,那么该字段必须同时在group by子句中出现;
2、如果没有group by子句,select列表中不允许出现字段(单行函数)与多行函数混用的情况
select empno, sal from emp; //合法
select avg(sal) from emp; //合法
select empno, avg(sal) from emp; //非法
3、不允许在where子句中使用多行函数
select deptno, avg(sal) from emp
where avg(sal) > 2000; //执行where时尚未执行groupby 及其他
group by deptno;
八、having子句
作用:对分组查询的结果进行过滤
注意1:having从句过滤分组后的结果,它只能出现在group by从句之后,而where从句要出现在group by从句之前。
注意2:where过滤行,having过滤分组。having支持所有where操作符。
举例:列出平均工资大于1000的部门ID
select deptno, avg(sal) from emp group by deptno having avg(sal) > 1000
order by deptno;