【ORACLE+PLSQL学习笔记#3】SQL 外连接表示辨识,where,from,select子查询+分页查询一些特点(有点绕)

左右外连接
SQL1999 写法:改变right/left即可以左右切换外连接,左连接代表以左边字段为根据查询,而无论右边字段是否有数据统一显示。反之亦然。

select ow.id,ow.name,year,month,money 
from t_owners ow left join t_account ac 
on ow.id=ac.owneruuid

ORACLE特有写法:’(+)‘位置在左表后即是右连接,’(+)'位置在右表后即是左连接

select ow.id,ow.name,year,month,money 
from t_owners ow , t_account ac 
where ow.id=ac.owneruuid(+)

以上皆是左外连接。
where子查询
跟在where条件之后,有单行和多行之分。单行多是复合函数处理结果,即单条记录,多行指返回一个表,即多条记录。

--单行子查询
select * from t_account where year='2012' and month='01'
and usenum>(select avg(usenum) from t_account where year='2012' and month='01')
--多行子查询
select * from t_owners where addressid in(1,3,4)
select * from t_owners where addressid not in(select id from t_address where name like '%花园%')

from子查询
from 后面接表,即多条记录。

--from子查询(返回的是一个表,即多条记录)
select * from(
select o.id 业主编号,o.name 业主名称,ot.name 业主类型
from t_owners o,t_ownertype ot where o.ownertypeid=ot.id )
where 业主类型='居民'

select子查询
跟在select后面,作为一个字段,即单条记录使用,值得注意的是需要以父级即上一层的from后接表的字段作为条件使用。

--select子查询(需要传递外表的字段作为指定查询条件,返回的是一个字段,这个结果是唯一的)
select id,name,
(select name from t_address where id=addressid) 详细地 ,
(select (select name from t_area where id=areaid ) 
from t_address where id=addressid) 所属区域名称 
from t_owners

分页查询
1.简单分页查询,只需要实现一层子查询,注意:初始生成rownum只能使用<或者<=比较运算符,要想实现第10条记录到第20条的查询,必须利用子查询优先生成rownum起别名才能利用‘>’进行筛选。

select * from (select rownum r,t.* from t_account t) where r<=20 and r>10

若是直接如下查询会直接报错:无法识别大于号>,输出异常
在这里插入图片描述
2.带有排序的分页查询,如图以usenum为降序输出11-20的记录。
在这里插入图片描述
如果直接进行下面尝试:

select * from (select rownum r,t.* from t_account t order by usenum desc) where r<=20 and r>10

会得到与上次查询所得相悖,是错误的输出记录,不是我们想要的结果:
在这里插入图片描述
原因在于,在生成rownum之后才进行排序,我们要想得到正确的结果,必须保证rownum生成在排序之后:

select * from 
       (select rownum r,t.* from 
               (select * from t_account t order by usenum desc) t
        ) 
where r<=20 and r>10

这样结果就和第一张图对上了
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值