1.最简单的查询方式
select * from emp;
select * from dept;
select empno, ename,sal from emp;
2.使用算术表达式
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语句中,对数值型数据可以使用算术运算符创建表达式。
3.使用字段别名
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可以省略
4.DISTINCT关键
缺省情况下,查询结果中包含所有符合条件的记录行,包括重复行
select deptno from emp;
使用DISTINCT关键字可从查询结果中清除重复行
select distinct deptno from emp;
select distinct job from emp;
DISTINCT的作用范围是后面所有字段的组合
select distinct deptno job from emp;
5.排序
排序方式包括升序(asc,缺省)和降序(desc)两种
5.1按单字段排序
select empno, ename, sal from emp order by sal;
select empno, ename, sal from emp order by sal desc ;
5.2按多字段排序
select deptno, empno, ename, sal from emp order by deptno, sal;
5.3使用字段别名排序
select empno, ename, sal*12 annsal from emp order by annsal;
5.4查询条件中使用逻辑运算符
select * from emp where deptno = 10 and sal > 1000; select * from emp where deptno = 10 or job = ‘CLERK’; select * from emp where sal not in (800, 1500, 2000);
6.SQL优化问题
- AND: 把检索结果较少的条件放到后面
- OR: 把检索结果较多的条件放到后面
7.四种运算符
共计四种运算符:算术>连接>比较>逻辑
优先级 | 运算符 |
---|---|
1 | *、 / |
2 | +、 - |
3 | || |
4 | =、 >、 >=、 <、 <=、 <> |
5 | is[not] null 、like 、[not]in |
6 | [not]between...and |
7 | not |
8 | and |
9 | or |
可使用小括号强行改变运算顺序
select * from emp where job='SALESMAN' or job='CLERK' and sal>=1280; select * from emp where (job='SALESMAN' or job='CLERK') and sal>=1280;
8.分页
当数据量过大时,在一页中查看数据是一件非常麻烦的事情
select * from 表名 limit start,count
从start开始,获取count条数据
start索引从0开始