mysql子查詢語句多列 MySQL 子查詢

2021-10-17 20:27:30 字數 2076 閱讀 9030

對於下表,

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建立多列索引語句 mysql多列索引詳解

建立多列索引 在t user表id,username,email欄位上建立多列索引 該錶只有此索引 alter table t user add index user index id,username,email 能夠利用該索引的查詢 符合leftmost index prefixes原則的查詢 ...

Mysql多列分組查詢 示列詳解

一張表 按照時間,按照時間,id分組 源表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 select flowdata.store id,flowdata.create hour as createhour,sum in count hourincoun...

關聯查詢 單行子查詢返回多列

例1 select from table1 where id select id from table1 由於子查詢結果中有多行,但是where條件id 只能有一行記錄 例2 select select name from emp where a.job b.job from emp 由於 子查詢的...