2. select
2.1查询行(记录)
--select 数据 from 数据源 where 行过滤条件;
--where
-- = != <> > < >= <=
--查询员工姓名为‘KING’的员工信息
select * from emp where ename='KING';
--查询员工姓名不为‘KING’的员工信息
select * from emp where ename!='KING';
select * from emp where ename<>'KING';
--not条件取反 and与 or或
--null 值不能使用=|!=判断 需要使用is判断
--查询有奖金存在的员工
select * from emp where not comm is null; --满足后面条件的结果集整体进行取反
select * from emp where comm is not null;
-- 值|字段 between 值1 and 值2 是否在后面的区间之间
--查询 薪资在1000~2000之间的员工姓名,员工编号,员工薪水,员工部门
select empno,ename,sal,deptno from emp where sal>=1000 and sal<=2000;
select empno,ename,sal,deptno from emp where sal between 1250 and 2000;
注意: 执行流程: from – where – select
2.1.1 some
--some(值列表) all(值1,值2,值3) any()
--查询比三个人薪资都高的员工信息 700,1000,1250
--大于最大值 小于最小值
select * from emp where sal > all(700,1000,1250);
--查询比三个人薪资任何一个高的员工信息 700,1000,1250
select * from emp where sal > any(700,1000,1250);
2.2 集合
-
Union,并集(去重) 对两个结果集进行并集操作,不包括重复行同时进行默认规则的排序
-
Union All,全集(不去重) 对两个结果集进行并集操作,包括重复行,不进行排序
select * from emp where job='SALESMAN' Union all select * from emp where sal>1500;
-
Intersect,交集(找出重复) 对两个结果集进行交集操作,不包括重复行,同时进行默认规则的排序
select * from emp where job='SALESMAN' Intersect select * from emp where sal>1500;
-
Minus,差集(减去重复) 对两个结果集进行差操作,不包括重复行,同时进行默认规则的排序
2.3 排序(order by )
-
排序: order by 默认升序
-
select 数据 from 数据源 where 行过滤条件 order by 排序字段 desc降序|asc升序,排序字段 …;
执行流程: from–where --select–order by
排序是对结果集中的数据做排序注意 : order by 后面可以使用字段别名指定字段做排序,因为执行流程的问题
-查询员工信息, select * from emp order by sal; --查询30部门的员工信息按照薪资做升序,薪资相同按照奖金做降序排序sql select * from emp where deptno = 30 order by sal,comm desc; --查询部门的员工信息以及年薪,根据年薪做降序排序 select empno,ename,(sal+nvl(comm,0))*12 total from emp order by total
2.4 子查询
子查询: 查询语句中嵌套查询语句
--查询与king同部门的员工信息 select * from emp where deptno = (select deptno from emp where ename='KING');
2.4.1 in(值列表)
--in(值列表) 判断某一个数据 是否在in(值列表中),如果存在就满足,不存在就不满足 select * from emp where deptno in (10,20);
2.5 单行函数
单行函数
-
sysdate/current_date 以date类型返回当前的日期
-
add_months(d,x) 返回加上x月后的日期d的值
-
LAST_DAY(d) 返回的所在月份的最后一天
-
months_between(date1,date2) 返回date1和date2之间月的数目 next_day(sysdate,星期一) 下一个即将要到来的星期一的日期
--日期可以进行+ - select sysdate 今天,sysdate+1 明天 from dual; select sysdate 今天,sysdate-30 明天 from dual; --查询每个员工的转正日期 3个月转正 select hiredate,hiredate+90 from emp; --月份 + - add_months(d,x) select hiredate, add_months(hiredate,-3) from emp; --last_day() 某个月的最后一天 select last_day(sysdate) from dual; --months_between(date1,date2) 月份差 select months_between(sysdate,hiredate)/12 from emp; --即将要过的星期几 select next_day(sysdate,'星期一') from dual; --to_char(日期对象,'格式模板') 日期对象转为字符串 --to_date(字符串,'格式模板') 字符串转为日期对象 -- '2008-12-12 13:05:12' 'yyyy-mm-dd hh24:mi:ss' select to_date('2008-12-12 13:05:12','yyyy-mm-dd hh24:mi:ss')+1 from dual; select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual; select to_char(sysdate,'yyyy"年"mm"月"dd"日" hh24:mi:ss') 今天 from dual;
-