Oracle:高级查询

单表中的联合查询

联合语句是指两个或多个select语句是并列关系,并且对这些select语句所捕获的记录进行集合操作,以获得最终的结果集。这些联合语句包括:union查询,union all查询,intersect查询和minus查询。

union查询

该操作符用于取得两个查询结果集的并集
当使用该操作符时,会自动去掉结果集中的重复行,语法结构如下:

select 语句1 union select 语句2

union all查询

该操作符与union相似,但是它不会取消重复行,不会排序。它可以将全部行并入结果中,其中包括重复行。如果未使用all关键字,则删除重复行。

intersect查询

intersect操作符用于两个查询结果的交集

子查询

子查询是指嵌套在查询语句中的查询语句。子查询出现的位置一般为条件语句,如where条件,它本质上是where后的一个条件表达式。Oracle会首先执行子查询,然后执行父查询
理解子查询子查询是嵌入在其它SQL语句中的select语句,也叫嵌套查询。子查询首先生成结果集并将结果集应用于条件语句。它可以出现在插入、查询、更新和删除语句中。建立子查询的目的在于更加有效地限制where子句中的条件,并可以将复杂的查询逻辑梳理得更加清晰。子查询与父查询的关系如下:

select 语句 where 条件= (select 语句 where条件)

子查询的使用 在select语句中,where子句或者having子句中的条件往往不能用一个确定的表达式来确定,而需要依赖另一个查询,这个被嵌套使用的查询就是子查询。子查询返回单行,其语法如下:

select 语句 where 条件 = (select 语句 where 条件)

子查询就是嵌套在另一个select语句中的查询,select语句一般总是用括号括起来。在子查询寻在还可以嵌套子查询。

子查询的使用方式及限制

在实际应用中,子查询一般出现在where子句中,包含子查询的语句通常采用

where 条件 [not] in (子查询)
where 条件 比较运算符 [not|all] (子查询)
where 条件 [not] extists (子查询)

使用in、any或all,结合比较运算符,可以引入表的列表操作;通过exists引入存在性测试。
子查询可以由一个比较运算符(=、<>、>、>=、<、<=)引入,由比较运算符引入的子查询必须返回单个值,而不是值列表。
1、比较运算符引入子查询

select order_id,discount_price from order_items
where order_id =
(select order_id from orders where customer_id = 101 and sales_rep_id = 159) 
and line_item_id = 1;

在查询的结果中,数据是唯一的,可以使用比较运算符。执行过程是,首先执行子查询,将执行的结果返回给主查询,然后根据条件执行主查询。
2、子查询中的聚合函数
可以将聚合函数作为where子句的搜索条件的一部分得到聚合函数返回的值。聚合函数返回的是单值,可以在比较运算符中引入子查询。

select order_id,line_item_id,unit_price from order_items where unit_price > 
(select avg(unit_price) from order_items)
and line_item_id = 1;

在子查询中使用in、all关键字
对于在子查询返回多个值的情况,可以使用in关键字。当使用in运算符引入子查询时,是对子查询集合成员测试,即把源表中的列值与子查询的返回结果进行比较,如果列值结果与返回结果集中的列数据值之一匹配,那么in判别式求值为true,查询结果就包含这行数据。

select order_id,discount_price 
from order_items
where order_id in
(select order_id from orders where customer_id = 101)
and line-item-id = 1

子查询返回多行。如果查询返回多行值,那么有时需要用到in关键字,除此之外也可使用some、any、all关键字。

select order_id,discount_price 
from order_items
where order_id all
(select credit_limit from customersnew where country = 'IT')
select order_id,discount_price 
from order_items
where credit_limit >
(select max(credit_limit) from customersnew where country = 'IT')

4、在子查询中使用exits关键字
在某些情况下,只需查询返回true或false,子查询的数据本身并不重要。这时,就可以使用exits判别式引入子查询。就相当于进行一次存在性测试。

select corder_id,discount_price from order_items or1
where exists
(select * from orders or2
where customer_id = 101 and or1.order_id = or2.order_id)
and line_item_id = 1;

查询语句优化

在查询中尽量不适用“*”
** 多表查询中尽量不适用别名**
条件查询多使用where
指定查询范围多使用in
子查询多使用exits语句判断条件

select corder_id,discount_price from order_items or1
where order-id in
(select order_id  from orders
where customer_id = 101)
and line_item_id = 1;
select corder_id,discount_price from order_items or1
where exists
(select * from orders or2
where customer_id = 101 and or1.order_id = or2.order_id)
and line_item_id = 1;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章