資料庫管理系統 (DBMS) 中的巢狀查詢詳解
一個巢狀查詢是指在其內部巢狀另一個查詢的查詢。巢狀的查詢稱為子查詢。
子查詢通常出現在查詢的WHERE 子句中。有時它也可能出現在FROM子句或HAVING 子句中。
示例
讓我們透過一個例子來學習巢狀查詢。
查詢regno=103的員工姓名
查詢如下:
select E.ename from employee E where E.eid IN (select S.eid from salary S where S.regno=103);
學生表
學生表建立如下:
create table student(id number(10), name varchar2(20),classID number(10), marks varchar2(20)); Insert into student values(1,'pinky',3,2.4); Insert into student values(2,'bob',3,1.44); Insert into student values(3,'Jam',1,3.24); Insert into student values(4,'lucky',2,2.67); Insert into student values(5,'ram',2,4.56); select * from student;
輸出
您將獲得以下輸出:
| ID | 姓名 | 班級ID | 分數 |
|---|---|---|---|
| 1 | Pinky | 3 | 2.4 |
| 2 | Bob | 3 | 1.44 |
| 3 | Jam | 1 | 3.24 |
| 4 | Lucky | 2 | 2.67 |
| 5 | Ram | 2 | 4.56 |
教師表
教師表建立如下:
示例
Create table teacher(id number(10), name varchar(20), subject varchar2(10), classID number(10), salary number(30)); Insert into teacher values(1,’bhanu’,’computer’,3,5000); Insert into teacher values(2,'rekha','science',1,5000); Insert into teacher values(3,'siri','social',NULL,4500); Insert into teacher values(4,'kittu','mathsr',2,5500); select * from teacher;
輸出
您將獲得以下輸出:
| ID | 姓名 | 科目 | 班級ID | 薪資 |
|---|---|---|---|---|
| 1 | Bhanu | 計算機 | 3 | 5000 |
| 2 | Rekha | 科學 | 1 | 5000 |
| 3 | Siri | 社會 | NULL | 4500 |
| 4 | Kittu | 數學 | 2 | 5500 |
班級表
班級表建立如下:
示例
Create table class(id number(10), grade number(10), teacherID number(10), noofstudents number(10)); insert into class values(1,8,2,20); insert into class values(2,9,3,40); insert into class values(3,10,1,38); select * from class;
輸出
您將獲得以下輸出:
| ID | 年級 | 教師ID | 學生人數 |
|---|---|---|---|
| 1 | 8 | 2 | 20 |
| 2 | 9 | 3 | 40 |
| 3 | 10 | 1 | 38 |
現在讓我們來處理巢狀查詢
示例1
Select AVG(noofstudents) from class where teacherID IN( Select id from teacher Where subject=’science’ OR subject=’maths’);
輸出
您將獲得以下輸出:
20.0
示例2
SELECT * FROM student WHERE classID = ( SELECT id FROM class WHERE noofstudents = ( SELECT MAX(noofstudents) FROM class));
輸出
您將獲得以下輸出:
4|lucky |2|2.67 5|ram |2|4.56
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP