一、select语句
Select 语句的整体形式:
select col1, col2… // 要查找的列名
from table_name // 要搜索哪张表
where condition // 设置查找条件
group by col… // 设置分组
having condtion // 设置分组条件
order by col… // 设置排序
下面举例说明具体用法:
(1)查询所有员工的所有记录
select * from emp
(2)查询 员工号,姓名,月薪,奖金,年薪
select empno, ename, sal, comm, sal*12 from emp;
(3) 对例 (2) 使用别名
select empno, ename, sal as 工资, comm 奖金, sal*12 "年 薪" from emp;
(4)查询员工号,姓名,月薪,奖金,年薪,年收入
select empno, ename, sal 工资, comm 奖金, sal*12 "年 薪", sal*12+nvl(comm, 0) "年收入" from emp;//nvl(a, b),如果 a 为空,则取 b 的值; a 不为空,取 a 的值
(5)查看员工表不同的部门编号
select distinct deptno from emp;//distinct去重,即没有重复数据
- 查看不同部门的不同工种 演示 distinct 作用范围
select distinct deptno, job from emp;//distinct 作用范围:作用于后面所有的列
(7)输出计算表达式 演示系统时间和伪表
select 3+20*5, sysdate from dual;//sysdate显示当前时间, dual:伪表 为了满足 SQL 语法,from 后必须跟表名
二、条件过滤
基本结构:
select .... from table where condtion;
具体用法如下:
(1)查询 10 号部门的员工信息
select * from emp where deptno = 10;
(2)查询员工名字为 KING 的员工信息
select * from emp where ename = 'KING'; //这里区分大小写
(3)查找薪水不等于 1250 员工的信息
select * from emp where sal != 1250;
select * from emp where sal <> 1250;//这两者等价
(4) 查询入职日期为 1981 年 11 月 17 日的员工信息
select * from emp where hiredate = '17-11 月-1981' ;//需要注意日期格式 NLS_DATE_FORMAT, 默认是 DD-MON-RR,也可以自己设定
(5)查询工资介于 1000-2000 之间的员工信息 演示 > >= < <=
select * from emp where sal>=1000 and sal<=2000;
select * from emp where sal between 1000 and 2000;//两者等价
三、逻辑运算符: or and not
(1) 查询 10 号部门或者 20 部门的员工信息
select * from emp where depton = 10 or depton = 20 ;
(2) 查询 10 号部门员工工资为 1300 的员工信息
select * from emp where depton = 10 and sal = 1300 ;
(3)查询 81 年 2 月(含 2 月)至 82 年 2 月(不含 2 月)
select * from emp where hiredate >= '01-2 月-81' and hiredate < '01-2 月-82' ;//这种情况无法使用 between and 进行查询
注意日期格式问题,注意月份单月不要在前面加 0,否则会报错
(4)查询奖金为空的员工信息为
select * from emp where comm is null; //where 条件后面若判断是否为空, 应该使用 is 或者 is not,不能用 = 或者 !=
(5)关于 and 和 or 短路问题的说明
对于 and 要把容易出现假的放在最右边,因为 and 右侧一旦为假,便不会在判断 and 左侧的真假,因此可以提高效率;同理,or 要把容易出现真的放在最右边
(6)查询 10 号部门和 30 号部门,工资为 1250 的员工信息
select * from emp where (deptno=10 or deptno=30) and sal=1250;//在有 or 和 and 的 where 条件中,and 的优先级比 or 高
注意:在 where 条件表达式中有 or 的时候, 应该使用 ( ) 括起来 。
四、集合运算符: in 和not in
(1)查询部门号是 10 或者 20 的员工信息
select * from emp where deptno in (10, 20, null);
(2)查询不是 10 和 20 号部门的员工信息
select * from emp where deptno not in (10, 20);
注意:
select * from emp where deptno not in (10, 20, null);
查不到记录。因为上句等价于
select * from emp where deptno!=10 and deptno!=20 and deptno!=null;
deptno!=null 等价于 null,因为 and,整个条件为假,按空条件查找,自然查不到记录
总结:在集合中用 in,不在集合中用 not in
in 后面可以出现 null; not in 后面的集合当中不要出现 null。
五、like 模糊查找
(1)查询员工首字母是 S 的员工信息
select * from emp where ename like 'S%';
(2) 查询员工编号为 79 开头的员工信息
select * from emp where empno like '79%';
(3)查询名字为四个字母长度的员工信息
select * from emp where ename like '____';
(4) 查询员工姓名带_的员工信息
select * from emp where ename like '%\_%' escape '\'; // escape '\' 表示 \ 是转义字符