1.别名

select ename 员工姓名,sal 工资收入,comm 奖金收入,sal*6+(sal+sal*0.2)*6+comm 总收入 from emp

2.distinct应用

  • 查询员工表中一共有哪几种岗位类型

select distinct job from emp

distinct:将job相同的记为一行

3.where应用

where+查询条件

select * from emp where deptno=10

  • 查询1987年6月1日之后入职的员工信息

select * from emp where hiredate>'1987-06-01

  • 查询查询1985年12月31日之前入职的员工姓名及入职日期

select ename,hiredate from emp where hiredate<'1985-12-31'

4.and or not 应用

  • 查询薪水1000到1500员工

select * from emp where sal>=1000 and sal<=1500

select * from emp where sal between 1000 and 1500

  • 查询job 为 SALESMAN或者MANAGER的员工信息

select * from emp where job='SALESMAN' or 'MANAGER'

select * from emp where job in('SALESMAN','MANAGER')

  • 查询奖金为空的员工信息

select * from emp where comm is null

  • 查询奖金不为空的员工信息

select * from emp where comm is not

  • 查询职位是SALESMAN或者是PRESIDENT 并且薪水>1500

select ename, job, sal from emp where (job='SALESMAN' or job='PRESIDENT') and sal>1500

  • 查询职位是PRESIDENT并且薪水>1500 或者 职位是SALESMAN

select ename, job, sal from emp where job='SALESMAN' or (job='PRESIDENT' and

5.模糊查询

  • 查询姓名首字母为W的员工信息

select * from emp where ename like 'W%'

  • 查询姓名以S结尾的员工信息

select * from emp where ename like '%S'

  • 查询姓名第二个字母是L的员工

select * from emp where ename like '_L%'    

(注释:其中 _ 为一个占位符,因为第二字母是L,第一字母未知,所以用_充当一个字母)

  • 查询员工姓名倒数第二个字母为T的员工信息

select * from emp where ename like '%T_'

(注释:其中 _ 为一个占位符 )

  • 查询姓名第三个字母是_的员工

select * from emp where ename like '__\_%'

select * from emp where ename like '__@_%' escape '@'

(注释:其中@标记后面紧跟的_表示 字母是_,而不是占位符,即第三个字母为_ ;@前的_为两个占位符)

 

补充:

关键字 LIKE 可用于实现模糊查询,常见于搜索功能中。

和 LIKE 联用的通常还有通配符,代表未知字符。SQL中的通配符是 _ 和 % 。其中 _ 代表一个未指定字符,% 代表不定个未指定字符

比如,要只记得电话号码前四位数为1101,而后两位忘记了,则可以用两个 _ 通配符代替:

SELECT name,age,phone FROM employee WHERE phone LIKE '1101__';

6.排序 order by    (asc 升序 desc降序   默认asc)

select * from emp order by sal desc,empno

  • 查询薪水最高的5个员工

select * from emp order by sal desc limit 5

  • 查询薪水最高的从第4个员工开始查询7个

select * from emp order by sal desc limit 3,7

  • 按照每页显示5条记录,分别查询第1页,第2页,第3页

第一页

select * from emp order by empno limit 0,5

第二页

select * from emp order by empno limit 5,5

补充:

如果后面不加 DESC 或 ASC 将默认按照升序排列。应用场景博客系统中按时间先后顺序显示博文

 

练习:

1.查询入职日期在1982年至1985年的员工信息

select * from emp where year(hiredate) between 1982 and 1985

2. 查询部门编号为10或者20的员工信息

select * from emp where deptno in(10,20)