SQL exists語法
Store_Information 表格
Store_Name Sales
Los Angeles 1500
San Diego 250
Los Angeles 300
Boston 700
Geography 表格
Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego
查詢1
select sum(`sales`) from `store_information` as s
where exists(
select * from `geography` as g
where `region_name` = 'West'
)
查詢2
select sum(`sales`) from `store_information` as s
where exists(
select * from `geography` as g
where `region_name` = 'West'
and s.`store_name` = g.`store_name`
)
說明
EXISTS 運算子可以連接子查詢,用來判斷子查詢是否有返回的結果,如果有結果返回則為真、否則為假。若 EXISTS 為真,就會繼續執行外查詢中的 SQL;若 EXISTS 為假,則整個 SQL 查詢就不會返回任何結果。
故查詢1返回外查詢的結果
reference
http://webdesign.kerthis.com/sql/sql_exists
留言
張貼留言