1. 程式人生 > >MySQL自學筆記4--where、from、exists型子查詢

MySQL自學筆記4--where、from、exists型子查詢

MySQL自學筆記

使用MySQL 5.5以及MySQL自帶命令客戶端

子查詢

定義:一個查詢是另外一個查詢的條件時,稱為子查詢。子查詢就是在原有的查詢語句中,嵌入新的查詢,來得到想要的結果集。根據子查詢的嵌入位置,可以分為三種子查詢:where型子查詢、from型子查詢、exists型子查詢

where型子查詢

將內層查詢的結果作為外出查詢的比較條件
典型的語法:

select * from table1Name
where colName = (select colName from table2Name where ...)
# 上面的table1Name和table2Name可以是一樣的,也可以是不一樣的
# 上面的句子中等號相當於符號in,如下: # where colName in (select colName from table2Name where ...)

舉一個例子:存在一個goods表,查詢裡面最新商品、最貴商品

select goods_id, goods_name
from goods
where goods_id = (select max(good_id) from goods);
# 查詢出最新的商品
select goods_id, goods_name, shop_price 
from goods
where shop_price in (select
max(shop_price) from goods group by cat_id);

from型子查詢

將內層的查詢結果當作臨時表,供給外出的SQL語句進行再次查詢。可以給臨時表起一個別名,用關鍵字as
典型的語法:

select * from (select * from  table1Name where ...) where ...

舉一個例子:有一張成績表stu,查詢兩門及兩門以上不及格同學的平均分

select name, avg(socre) from stu where name in (select name from (select name, sum
(score < 60) as temp1 from stu group by name having temp1 > 1) as temp2) group by name;

exists型子查詢

將外層的查詢結果拿到內層,看內層的查詢是否成立。該查詢實際上不返回任何的資料,而是返回True或False。該查詢可以與in型子查詢互換,但是該查詢效率高。
典型的語句:

select * from table1Name
where exists (select * from table2Name where ..)

舉一個例子:對於goods表和category表,查詢有商品的欄目

select cat_id, cat_name from category where exists (select * from goods where goods.cat_id = category.cat_id);