1. 基础的查询操作 #简单查询 select * from emp; //查询emp中所有的记录 select empno, job,ename from emp; //查询emp表中的某些字段 select ename as 名字 from emp; //使用字段别名 去重 distinct
select distinct deotno from emp; //去除重复的行(针对字段而言) 排序 order by
#默认是升序(asc),降序(desc) select * from emp order by sal desc; //以工资按降序排序 select * from epm order by sal , deptno //多字段排序 select sal*12 annsal from epm order by annsal //别名排序 条件查询 where
select * from emp where sal>1000; //工资大于1000的 select * from emp where sal>1000 and sal<2000; select * from emp where sal>5000 or sal<1000 select * from emp where sal<>2500 //工资不等于2500 select * from emp where sal is null //工资不空的 select * from emp where sal>0 or 1=1; //恒等式 ps:运算符的优先级:算术>连接>比较>逻辑
分组查询(group by) 描述:将表中的数据分成若干个小组 语法:select 字段 from where 条件 group by 字段 order by 字段
#例: select 字段 from where 条件 group by 字段 order by 字段 ps:在group by 分组,select 子句,不能写group by没有的字段。除非这些字段用在聚合函数中 过滤 having 描述:过滤分组之后的结果,只能出现在group by 的后面
#例: select deptno , count(1),avg(sal) from emp group by deptno having avg(sal) >2000 select avg(sal) avg_sal,deptno from emp group by deptno having avg_sal>2000; 执行过程:from –where –group by --- having –select ---order by 分页
#例: select * from emp where sal>2000 union select * from emp where deptno>20 select * from emp where sal>2000 union all select * from emp where deptno>20 使用要求:联合的结果集必须一致(两张表一致,查询的字段也一致),不然会发生错误。