共計(jì) 1741 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。
自動(dòng)寫代碼機(jī)器人,免費(fèi)開通
這篇文章主要介紹 mysql 數(shù)據(jù)庫中子查詢的示例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
mysql 子查詢是什么?
子查詢,又叫內(nèi)部查詢,相對(duì)于內(nèi)部查詢,包含內(nèi)部查詢的就稱為外部查詢。子查詢?cè)试S把一個(gè)查詢嵌套在另一個(gè)查詢當(dāng)中。
mysql 數(shù)據(jù)庫子查詢語句的特點(diǎn):任何可使用表達(dá)式的地方,都可以使用子查詢,只要他返回的是單個(gè)值;子查詢按返回值的數(shù)量,子查詢對(duì)外部依賴性,比較運(yùn)算符的不同性進(jìn)行分類;這在分頁查詢 sql 語句中經(jīng)常用到。
一:子查詢的特點(diǎn):
子查詢可被嵌套在 select,insert,update,delete 等語句中
大多數(shù)情況下子查詢充當(dāng)中間結(jié)果集角色
子查詢可進(jìn)行嵌套,且根據(jù)內(nèi)存及表達(dá)式復(fù)雜程度不同,嵌套限制也不同
任何可使用表達(dá)式的地方,都可以使用子查詢,只要他返回的是單個(gè)值
二:子查詢的分類:
按返回值的數(shù)量可分為:標(biāo)量子查詢,多值子查詢
按子查詢對(duì)外部依賴性:獨(dú)立子查詢,相關(guān)子查詢
按比較運(yùn)算符的不同性:IN,EXISTS,ANY,SOME,ALL 等多種形式
三:子查詢的使用:
首先創(chuàng)建兩個(gè)表(學(xué)生表和教師表)
# 創(chuàng)建學(xué)生表
mysql create table tb_student(
- stu_ID long,
- class varchar(5),
- score int
- );
Query OK, 0 rows affected (0.23 sec)
# 創(chuàng)建教師表
mysql create table tb_teacher(
- tea_ID long,
- class varchar(5),
- age int
- );
Query OK, 0 rows affected (0.49 sec)
將一些值插入到表中
insert into tb_student values(1, A , 20);
insert into tb_student values(2, A , 30);
insert into tb_student values(3, A , 70);
insert into tb_student values(4, B , 60);
insert into tb_student values(5, B , 70);
insert into tb_student values(6, B , 80);
insert into tb_teacher values(1, A , 25);
insert into tb_teacher values(2, B , 40);
準(zhǔn)備工作完畢,接下來進(jìn)行子查詢練習(xí)
例一:各班教師 ID 及其班級(jí)平均分?jǐn)?shù)
mysql select tea_ID,
- (select avg(score) from tb_student as s where s.class = t.class group by class)
- as Avg from tb_teacher as t;
+--------+---------+
| tea_ID | Avg |
+--------+---------+
| 1 | 40.0000 |
| 2 | 70.0000 |
+--------+---------+
2 rows in set (0.00 sec)
例二:各班級(jí)教師年齡及其班級(jí)及格人數(shù)(60 為及格線)
mysql select age,
- (select count(*) from tb_student as s where s.class = t.class s.score = 60 group by class)
- as Count from tb_teacher as t order by Count desc;
+------+-------+
| age | Count |
+------+-------+
| 40 | 3 |
| 25 | 1 |
+------+-------+
2 rows in set (0.00 sec)
以上是“mysql 數(shù)據(jù)庫中子查詢的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注丸趣 TV 行業(yè)資訊頻道!
向 AI 問一下細(xì)節(jié)