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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章