1. 程式人生 > >MySQL:子查詢

MySQL:子查詢

where lin 寫到 emp alt 量子 允許 lun 位置

對於下表,

技術分享

1. 場景:查詢代課天數最多的老師的信息。

方法一:select % from teacher order by days desc limit 1 ;

技術分享

該方法有漏洞:授課天數最多的老師實際上有兩位:Hanna和Luna。

直接設置limit 1會限制只輸出1位老師。而實際我們不知道有幾個代課最多的老師,不知道怎麽設置 limit。

【改進】分兩步完成:

第一步:先獲得代課天數最多的天數:select max(days) from teacher ;

第二步:再判斷哪個老師的代課天數與最大值是相同的。

MySQL允許將第一步的查詢結果作為一個值保存起來使用:

var1 = select max(days) from teacher;

select * from teacher where days = var1 ;

以上兩句相當於 select * from teacher where days = (select max(days) from teacher) ;

技術分享

【定義】如果一個查詢語句出現在另一個語句(不一定是查詢語句)內部,則第一個語句稱為子查詢

要求:子查詢語句必須使用括號。

優點:可以將目標拆分成幾步。

2. 分類標準(不同的分類,會有不同的使用方式)。

① 子查詢出現的位置。

· where 型:出現在where後; · from 型:出現在 from 後; · exists 型:出現在exists 後。

② 子查詢的返回值形式。

· 單一值: · 一列: · 多列: · 表(多行多列)。
3. 如何使用

① 標量子查詢。

② 列子查詢(使用集合類的操作符完成 in | not in | any | all | some)。

【舉個栗子】檢索所有帶過‘php0228’班的老師們帶過的班級信息。

【分析】第一步:select t_name from teacher where c_name=‘php0228‘;

第二步:select t_name,c_name,days from teacher where t_name in (select t_name from teacher where c_name=‘php0228‘);

技術分享

tip: = any 相當於 in; != all 相當於 not in

③ 返回一行(limit 1)

【舉個栗子】查找帶過0331班,與Linda具有相同代課天數的老師。

【分析】select t_name,gender,c_name from teacher where (gender,c_name)=(select gender,c_name from teacher where t_name=‘Linda‘ and c_name=‘php0331‘);

以上稱為“行子查詢”,不太常用。

④ 返回一個表:

select * from (select t_name,c_name,days from teacher where days>15) as temp ;

若只寫到(子查詢語句),則返回的是多行,需要給這幾行命名,用 as+【臨時名稱】即可。

tip: 關鍵字 as 可以用來起別名,例如 select t_name as teach from teacher ;//相當於給t_name起了別名teach。

⑤ exists 子查詢。

使用方法:exists(子查詢語句)

判斷依據:若子查詢可以返回數據,則認為exists表發誓返回真;

否則,返回假。

MySQL:子查詢