[亲测]Oracle查询--子查询,分页查询(二)

ORACLE查询(子查询,分页查询)

一、子查询

(一)单行子查询 ( 只返回一条记录 )

1 .查询 2012 年 1 月用水量大于平均值的台账记录
select * from t_account where usenum > 
(select avg(usenum) from t_account where  year = '2012' and month = '01' );

结果:
[亲测]Oracle查询--子查询,分页查询(二)

(二)多行子查询 ( 返回了多条记录 )

in 运算符
1. 查询地址编号为 1 、3 、4 的业主记录
select * from t_owners  where addressid in (1,3,4) ;

结果:
[亲测]Oracle查询--子查询,分页查询(二)

2 .查询地址含有“花园”的业主的信息
select * from t_owners where addressid in ( select id from t_address where name like '%花园%');

结果:
[亲测]Oracle查询--子查询,分页查询(二)

3. 查询地址不含有“花园”的业主的信息
select * from t_owners where addressid not in (select id from t_address where name like '%花园%');

结果:
[亲测]Oracle查询--子查询,分页查询(二)

4 .查询 2012 年台账中,使用量大于 2012 年3 月最大使用量的台账数据
select * from t_account where year = '2012' and usenum >
(select max(usenum) from t_account where year = '2012' and month = '03');

结果:
[亲测]Oracle查询--子查询,分页查询(二)

(三)嵌套子查询 ( 在子查询中再嵌套子查询 )

1.查询在海淀区的小区名字中含有花园的业主记录
select * from t_owners ow 
where addressid in 
(select ar.id from t_area ar , t_address ad 
where ar.id = ad.areaid and ar.name = '海淀' and ad.name like '%花园%');

结果:
[亲测]Oracle查询--子查询,分页查询(二)

(四)标量子查询 ( 子查询的语句执行的结果直接作为主查询的结果显示 ) 标量子查询实现 : dual 专门用来呈现数据

1. 查询台账表中的用户年用水量的总和 以及 年平均用水量
-- 方式一
select sum(usenum),avg(usenum) from t_account ;
-- 方式二
select (select sum(usenum) from t_account) 年用水 ,  (select avg(usenum) from t_account)  年均用水 from dual;

结果:
[亲测]Oracle查询--子查询,分页查询(二)

(五)相关子查询 ( 子查询需要依赖主查询 )

1. 查询显示业主编号,业主名称、地址和业主类型
--  方式一
select os.id ,os.name,ad.name, ow.name from t_owners os ,t_address ad,t_ownertype ow;
--  方式二
select os.id , os.name 业主名 ,
(select name from t_address where id = os.addressid)  地址,
(select name from t_ownertype where id= os.ownertypeid) 业主类型
from t_owners os;

结果:
[亲测]Oracle查询--子查询,分页查询(二)

四、分页查询

(一)简单分页
1.分页查询台账表 T_ACCOUNT,每页 10 条记录
select * from t_account where Rownum <= 10;

结果:
[亲测]Oracle查询--子查询,分页查询(二)

1.分页查询台账表 T_ACCOUNT,每页 11 - 20 条记录
select a.* from 
(select rownum rn,ac.* from t_account ac) a
where rn between 11 and 20;

结果:
[亲测]Oracle查询--子查询,分页查询(二)

(二)基于排序的分页
1.基于排序 分页查询台账表 T_ACCOUNT ,每页 11 - 20 条记录
select a.* from 
(select rownum r,t.* from 
        (select * from t_account order by money asc) t) a
where a.r between 11 and 20;

结果:
[亲测]Oracle查询--子查询,分页查询(二)