当前位置:网站首页>Zero foundation self-study SQL course | sub query
Zero foundation self-study SQL course | sub query
2022-06-24 09:14:00 【Meow Ningyi】
Hello everyone , I'm Ning Yi .
Today's talk SQL Course No 18 course : Subquery .
SQL Statements can be nested , The most common is the nesting of query statements .
Basic grammar :
SELECT < Field name >
FROM < Table name >
WHERE(
SELECT < Field name >
FROM < Table name >
);We generally call nested statements outside the main query , The nested statements are sub queries , Sometimes it is called external query 、 Internal query , You know what it means .
Subqueries should be enclosed in brackets . Subqueries can not only be placed in WHERE Behind , It can also be placed in SELECT、FROM Behind , Let's talk about it one by one .
1、 Subquery +WHERE Clause
SQL Execution time , The subquery in parentheses will be executed first , Subqueries are most often associated with WHERE Clause is used in conjunction with . The result of the subquery is as WHERE The filter condition of clause , Complete more complex data retrieval .
example : stay Students In the table , Find out what's going on in " Ning Yi " Students born later .

Instance analysis : You need to make sure " Ning Yi " My birthday , Then take birthday as WHERE filter , Get the final data .
First step : find " Ning Yi " My birthday
SELECT Sage
FROM Students
WHERE Sname = " Ning Yi "
The second step : Take birthday as WHERE filter , Get the final data , Subquery statements should be enclosed in parentheses .
SELECT *
FROM Students
WHERE Sage > (
SELECT Sage
FROM Students
WHERE Sname = " Ning Yi "
)
2、 Subquery + SELECT sentence
Subqueries can also be associated with SELECT Statement combination , The results returned by the subquery , Will be displayed as a column in the result set .
SELECT Subqueries of statements are often used in conjunction with aggregate functions . Because when we use aggregate functions , The record will be combined into one , Other data details cannot be displayed .
such as : We want to see all the student names in the student table 、 Student's birthday 、 Student's biggest birthday .
Sample results :

Wrong writing :
SELECT Sname,Sage,Max(Sage)
FROM StudentsIt would be wrong to write like this , Because aggregate functions and columns in other tables (Sname,Sage), At the same time SELECT Behind . Need to use GROUP BY Statement to list the columns in these tables (Sname,Sage) grouping .
Add... After the above statement GROUP BY Sname,Sage That's all right. .
But write like this , The data of each group will be aggregated into 1 Data , For example, each group has 3 Data , Using aggregate functions MAX()+GROUP BY, Finally, each group will only show 1 Data of maximum values .
We need to show Students All the students in the table , This is not enough to meet our needs .
Write it correctly : Combined with sub query to realize .
SELECT
Sname,
Sage,
(SELECT Max(Sage) FROM Students) AS Maxage
FROM Students3、 Subquery +FROM Clause
Subquery and FROM Clause is used in conjunction with , The subquery result is treated as a “ surface ”, It can be used SELECT Statement for further screening .
such as : Let's write one first SELECT Query statement
SELECT
Sid,
'student' AS status
FROM Students
WHERE Sid <= 5
Put the above query statement in FROM Behind , Then the result of the above query , Will be regarded as a “ surface ”.
SELECT Sid,status
FROM (
SELECT
Sid,
'student' AS status
FROM Students
WHERE Sid <= 5
) AS s -- Alias is required
WHERE Sid > 2Here's one thing to pay special attention to , Put it in FROM The following subquery , Must be aliased .

Complex subqueries are nested into FROM It makes the whole query look too complicated , We usually save the sub query results as views , Then directly use the view as the source table , View meeting SQL In the advanced course, we will explain in detail .
In fact, subquery is query statement nesting , There's nothing new , Just one more level , From the inside out, it will be clear .
Homework : combination Students surface , from Teachers Find the teacher who is the head teacher in the table ( Through sub query ).

Homework analysis : First from Students In the table , Find out the names of all the class teachers Tid And remove the weight , Use query results as filter criteria , Put it in WHERE In the sentence .
SELECT *
FROM Teachers
WHERE Tid IN (
SELECT
DISTINCT Tid
FROM Students
)Click on Focus on , Update the course and notify the first time ~
边栏推荐
- uniapp 开发多端项目如何配置环境变量以及区分环境打包
- MySQL | store notes of Master Kong MySQL from introduction to advanced
- 牛客网 实现简单计算器功能
- Redis implements a globally unique ID
- Pytoch read data set (two modes: typical data set and user-defined data set)
- 2021-05-20computed and watch applications and differences
- P6698-[BalticOI 2020 Day2]病毒【AC自动机,dp,SPFA】
- 【LeetCode】541. Reverse string II
- [ES6 breakthrough] promise is comparable to native custom encapsulation (10000 words)
- Opencv daily function structure analysis and shape descriptor (7) finding polygon (contour) / rotating rectangle intersection
猜你喜欢

Data middle office: middle office architecture and overview

Some common pitfalls in getting started with jupyter:

Alibaba Senior Software Testing Engineer recommends testers to learn -- Introduction to security testing

Easyexcel single sheet and multi sheet writing

支持向量机(SVC,NuSVC,LinearSVC)

uniapp 开发多端项目如何配置环境变量以及区分环境打包

荐书丨《好奇心的秘密》:一个针尖上可以站多少跳舞的小天使?

Numpy numpy中的np.c_和np.r_详解

Numpy NP in numpy c_ And np r_ Explain in detail

12、 Demonstration of all function realization effects
随机推荐
L01_一条SQL查询语句是如何执行的?
十二、所有功能实现效果演示
Every (), map (), forearch () methods. There are objects in the array
[redis realize Secondary killing Business ①] Overview of Secondary killing Process | Basic Business Realization
Redis实现全局唯一ID
Redis implements a globally unique ID
Remote connection of raspberry pie without display by VNC viewer
The list of open source summer winners has been publicized, and the field of basic software has become a hot application this year
听说你还在花钱从网上买 PPT 模板?
Sword finger offer 55 - I. depth DFS method of binary tree
Scheme of alcohol concentration tester based on single chip microcomputer
Leetcode -- wrong set
随笔-反思
2022.6.13-6.19 AI行业周刊(第102期):职业发展
Ebanb B1 Bracelet brush firmware abnormal interrupt handling
Alibaba Senior Software Testing Engineer recommends testers to learn -- Introduction to security testing
Support vector machine (SVC, nusvc, linearsvc)
Transplantation of xuantie e906 -- fanwai 0: Construction of xuantie c906 simulation environment
牛客网 实现简单计算器功能
【ES6闯关】Promise堪比原生的自定义封装(万字)