2013年12月11日 星期三

MSSQL子查詢

資料來源
資料來源
一、SQL 子查詢
進行資料表(含本身)查詢,除了可以使用Join外,還可以使用SQL 子查詢(Subquery),所謂的子查詢就是在select之間再放一個select 查詢指令,通常是位於 select 與 where 都可以插入子查詢,在WHERE使用子查詢主要目的是取得其他資料表紀錄的欄位值來建立WHERE句的條件運算式

二、使用子查詢注意事項

1.子查詢要在括號()中。
2.通常子查詢SELECT只會取得單一欄位的值,以便主查詢的欄位進行比較運算。
3.如需排序,子查詢不能使用ORDER BY,只能使用GROUP BY 子句。
4.如果子查詢可以取得多筆資料,在主查詢需使用IN邏輯運算子。
5、如果你想用一行指令是可以做到的:
select * from Table1 where ID in (select ID from Table1 group by ID having count(ID) >1 )

一行指令就做到看起來很神奇,不過請注意執行速度的問題,因為它對每一筆資料都作了子查詢,想想看如果你的 Table1 有一百萬筆資料,那是多麼可怕的事情!

從系統效益面來看,過濾重複 ID 是一個經常需要處理的狀況,如果先將「select ID, count(ID) as IDCount from Table1 group by ID」這個動作建立一個「Query1」,再用下面的指令來過濾資料就會比較有效率:

select Table1.* from Table1 inner join Query1
on Table1.ID = Query1.ID and Query1.IDCount > 1

這個指令在執行時「Query1」的查詢結果會先建立並且只執行一次,然後這個暫存結果才會與 Table1 作 Inner Join。

三、語法
SELECT 欄位名稱1,欄位名稱2,...,欄位名稱n 
FROM 資料表名稱1
WHERE 欄位名稱 = 
(SELECT 欄位名稱 FROM 資料表名稱2 WHERE 條件)

四、範例
範例1:
select count( * ) as 訂單數 
from orders
where customerID = (select id from Customers where name = 'apple')

範例2:
select *,(select avg(price) from Products )as 平均值 from Products  where price > (select avg(price) from Products)

範例3:
EXISTS指令:可以判斷子查詢的結果有沒有回傳資料,若有則會執行查詢中的結果。
select * from Customers where exists(select customerID from orders where customerID=Customers.id and (select count(*) from Orderdetial where orderID=orders.id and productID=1 )>0)

範例4:
select * from Orderdetial where exists(select * from Products where (name='糖果' or name='牛奶糖')and id = Orderdetial.productID )

範例5:
select * from Products where id not in (select productID from Orderdetial where orderID=2)

範例6:
select * from Products where id in (select productID from Orderdetial where orderID in (select id from orders where id ='1'))

沒有留言: