文章目录
检索数据
select {[distinct] 列名...}
from 表名
[where 选择条件]
[group by 列名]
[having 选择条件]
[order by 列名]
一、简单查询
只包含select子句和from子句的查询就是简单查询
1、检索所有的列 *
例1:查询dept表中所有的数据
select * from dept;
例2:查询表dept和salgrade
select * from dept,salgrade
2、检所指定的列
格式:select 列名1,列名2... from 表名;
例:在scott模式下,检索emp表中指定列(job,ename,empno)
select job,ename,empno from emp;
补充:ROWID:行标识符,是Oracle数据库内部使用的隐藏列
案例:检索emp表指定的列job和ename,还包括rowid伪列
select rowid,ename,job from emp;
3、带有表达式的select子句
算术运算符:±*/()
例:检索emp表的sql列,把其值调整为原来的1.1倍
select sal*(1+0.1),sal from emp;
select sal 原有工资,sal*(1+0.1) 现有工资 from emp;
4、为列指定别名
两种:as 关键字;直接指定列名
即:select 列名 别名 from 表名;
select 列名 as "别名" from 表名;
例:检索emp表的指定列(empno,ename,job),并使用as关键字为这些列指定中文别名(员工编号,员工名称,职务)
select empno as "员工编号",ename as "员工名称",job as "职务" from emp;
或
select empno as 员工编号,ename as 员工名称,job as 职务 from emp;
二、筛选查询
在select语句中,where子句位于from子句之后,其语法格式如下:
select 列名
from 表名
where 选择条件
条件查询:where关键词
格式:select 列名|* from 表名 where 选择条件;
例:查询工资高于1200的有哪些人?
select * from emp where sal>1200;
(1)all:只有与所有的元素比较值都为true,才返回数据行
格式:select 列名 from 表名 where 列名 比较运算符all(值1,值2,值3...);
案例:使用all关键字过滤工资(sal)同时不等于3000,950,800的员工记录
select empno,sal,ename from emp
where sal != all(3000,950,800);
注意:在进行比较筛选的时候,字符串和日期必须使用单引号标识。
(2)判断字段中是否存在内容:
- 内容为空:is null
例:查询每月可以得到奖金的雇员信息
select * from emp where comm is not null;
- 内容不为空:is not null
例:查询没有奖金的雇员
select * from emp where comm is null;
注意:
a.如果查询出现多个条件,在where语句之后,条件与条件之间用and进行连接
例:要求查询出,基本工资大于1500,同时可以领取奖金的雇员信息
select *
from emp
where sal>1500 and comm is not null;
b.满足其中一个条件,使用关键字or来进行连接
例:查询出基本工资大于1500,或者可以领取奖金的雇员信息
select *
from emp
where sal>1500 or comm is not null;
(3)NOT关键字:取反,把真的条件变为假,假的变为真
格式:select 列名 from 表名 where not(条件);
例:查询出基本工资不大于1500,同时不可以领取奖金的雇员信息
select *
from emp
where not(sal>1500 or comm is not null);
或
select *
from emp
where sal<=1500 and comm is null;
例:查询基本工资大于1500,但是小于3000的全部雇员信息
select *
from emp
where not(sal<=1500 or sal>=3000);
或
select *
from emp
where sal>1500 and sal<3000;
三、范围查询
指定范围查询的过滤语句:between…and…
格式:select 列名|* from 表名 where 列名 between 最小值 and 最大值;
select 列名|* from 表名 where 列名 not between 最小值 and 最大值;
例:查询工资在1500和3000之间的员工信息情况
select * from emp where sal between 1500 and 3000;
Oracle对数据的大小写是非常敏感的:
注意:除了上述语法外,还有in操作符不仅可以用在数字上,还可以用在字符串信息上
格式:
在列表内:where 列名 in(值1,值2...)
不在列表内:where 列名 not in(值1,值2...)
例:要求查询出姓名是SMITH、ALLEN、KING的雇员信息
select * from emp where ename in(SMITH,ALLEN,KING);
例:查询出雇员编号不是7369,7499,7521的雇员的具体信息
select *
from emp
where empno not in(7369,7499,7521);
四、模糊查找LIKE
即:输入一个指定关键字,把符合的内容全部查询出来
%:可以匹配任意长度的内容分;
_:可以匹配一个长度的内容
格式:where 列名 like '字符匹配符'
例:查询出所有雇员姓名中第二个字母包含“M”的雇员信息
select *
from emp
where ename like '_M%';
LIKE还可以方便进行日期的查找功能
例:查询雇佣日期包含81的雇员信息
select *
from emp
where hiredate like '%81%';
扩展:在like前面也可以加上not,表示否定的判断
NOT LIKE 不要匹配到的内容
例:查询出不要雇员姓名中第二个字母包含“L”的雇员信息
select *
from emp
where ename not like '_L%';