- 全表查询:select * from 表名;
-- 单表查询(虚拟结果集)
select * from emp;
- 查询指定列:select 字段1[,字段2,…] from 表名;
-- 查询指定列:查询emp表中ename,job,sal
select ename,job,sal from emp;
- 别名的设置:select 字段名 [as] 列别名 from 原表名 [as ]表别名;(as 可省略)
-- 设置别名:查询每位员工调整后的薪资(基本工资+1000)
select *,sal+1000 from emp;
select *,sal+1000 as tiaoxin from emp;
-- 练习:查询每位员工的年薪(基本工资*12):empno,ename,年薪
select empno, ename, sal*12 as 年薪 from emp;
- 查询不重复的记录:select distinct 字段名 from 表名;
-- 查询不重复的数据:查询emp表中有哪些部门
select distinct deptno from emp;
select distinct deptno,job from emp;-- distinct多字段去重时位于第一个字段的前面
- 条件查询:select 字段1[,字段2,…] from 表名 where 查询条件;
-- 条件查询
-- 查询基本工资大于等于2000小于等于3000的员工信息
select *
from emp
where sal >=2000 and sal <=3000;
select *
from emp
where sal between 2000 and 3000;
-- 查询10号部门和20号部门中sal低于2000的员工信息
select *
from emp
where (deptno = 20 or deptno = 10) and sal < 2000;
select *
from emp
where deptno in (10,20) and sal < 2000; -- in deptno取10或20,or条件过多可使用in简化代码
-- 练习:查询salesman的所属部门:姓名,职位,所在部门
select ename,job,deptno
from emp
where job = 'salesman';
- 空值查询:select 字段1[,字段2,…] from 表名 where 空值字段 is[ not] null;
-- 空值查询
-- 查询mgr为空的记录
select *
from emp
where mgr is null; -- null值与任何类型的数据类型判断、计算都为null
-- 用is来判断是否为空,不能用“=”判断
select *
from emp
where mgr is not null;
-- 用 is not 判断非空
-- 练习:查询comm不为空的记录
select *
from emp
where comm is not null;
前面的查询都是精确查询
- 模糊查询: select 字段1[,字段2,…] from 表名 where 字符串字段[ not] like 通配符;
百分号(%)通配符:匹配多个字符
下划线(_)通配符:匹配一个字符
模糊查询只能用于字符串类型的字段
-- 模糊查询
-- 查询姓名以a开头的员工信息
select *
from emp
where ename like 'a%';
-- 查询姓名中包含a的员工信息
select *
from emp
where ename like '%a%';# 不确定a的前后有多少个字符
-- 查询姓名中第二个字符为a的员工信息
select *
from emp
where ename like '_a%';# a的前面有一个字符,用‘_’
# 第三个字符为a '__a%'
-- 练习:查询员工姓名中不包含s的员工信息
select *
from emp
where ename not like '%s%';