mysql子查詢是什麼?
子查詢,又叫內部查詢,相對於內部查詢,包含內部查詢的就稱為外部查詢。子查詢允許把一個查詢嵌套在另一個查詢當中。
mysql資料庫子查詢語句的特點:任何可使用表達式的地方,都可以使用子查詢,只要他傳回的是單一值;子查詢按傳回值的數量,子查詢對外部依賴性,比較運算子的不同性進行分類;這在分頁查詢sql語句中常用到。
子查詢可被巢狀在select,insert,update,delete 等語句中
大多數情況下子查詢充當中間結果集角色
子查詢可進行嵌套,且根據記憶體及表達式複雜程度不同,嵌套限制也不同
任何可使用表達式的地方,都可以使用子查詢,只要他回傳的是單一值
按傳回值的數量可分為:標量子查詢,多值子查詢
按子查詢對外部依賴性:獨立子查詢,相關子查詢
依比較運算子的不同性:IN,EXISTS,ANY,SOME,ALL等多種形式
# 创建学生表 mysql> create table tb_student( -> stu_ID long, -> class varchar(5), -> score int -> ); Query OK, 0 rows affected (0.23 sec) # 创建教师表 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);
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)
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子查詢是什麼? mysql資料庫子查詢實際使用範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!