【WEEK6】 【DAY2】DQL Data Querying - Part Two 【English Version】

2024.4.2 Tuesday
Following the previous article 【WEEK6】 【DAY1】DQL Data Query - Part One【English Version】

Contents

  • 4.4. Join Queries
    • 4.4.1. JOIN Comparison
    • 4.4.2. Seven Types of JOINs
    • 4.4.3. Examples
      • 4.4.3.1. In this example, the results of INNER JOIN and RIGHT JOIN are the same
      • 4.4.3.2.LEFT JOIN
      • 4.4.3.3. querying students who missed exams
      • 4.4.3.4. Exercise: Query Information of Students Who Took Exams (Student ID, Student Name, Subject Name, Score)
      • 4.4.3.5. Self-Join (For Understanding)
        • A table joins itself, essentially splitting into two identical tables
        • Query the Grade of Students (Student ID, Name, Grade Name)
        • Query the Grade of Subjects (Subject Name, Grade Name)
        • Query Information of Students Who Took 'Advanced Mathematics-1' Exam (Student ID, Student Name, Subject Name, Score)
  • 4.5. Sorting and Pagination
    • 4.5.1. Sorting
      • 4.5.1.1. ORDER BY: Which field to sort by and how
    • 4.5.2. Pagination
      • 4.5.2.1. Displaying data skipping the top five scores in descending order
      • 4.5.2.2. Query the top 10 students by score in 'Advanced Mathematics-3', with scores no less than 80 (Student ID, Name, Course Name, Score)
  • 4.6. Subqueries
    • 4.6.1. Query all exam results for 'Advanced Mathematics-3' (Student ID, Course Number, Score) in descending order
      • 4.6.2.1. Method 1: Using join queries + subqueries
      • 4.6.1.2. Method 2: Using subqueries (Inside-out approach)
    • 4.6.2. Query student ID and name for students scoring above 80 in 'Advanced Mathematics-4'
      • 4.6.2.1. Method 1: Using join queries + subqueries
      • 4.6.2.2. Method 2: Using Join Queries
      • 4.6.2.3. Method 3: Using Subqueries
    • 4.6.3. Exercises
      • 4.6.3.1. Query the top 5 students' scores in C Language-1 (Student ID, Name, Score)
      • 4.6.3.2. Using a subquery, find the grade name where student Liu Fu is enrolled

4.4. Join Queries

4.4.1. JOIN Comparison

Operator NameDescription
INNER JOINReturns rows if there is at least one match in the tables
LEFT JOINReturns all rows from the left table, even if there are no matches in the right table
RIGHT JOINReturns all rows from the right table, even if there are no matches in the left table

4.4.2. Seven Types of JOINs

Insert image description here

4.4.3. Examples

/*
Join QueriesTo query data from multiple tables, connection operators can be used to perform multiple queries.
Inner joinQueries the intersection of the result sets of two tables.
Outer joinLeft outer join(Using the left table as the base, the right table is matched one by one. If there is no match, the records from the left table are returned, and the right table is filled with NULL.)Right outer join(Using the right table as the base, the left table is matched one by one. If there is no match, the records from the right table are returned, and the left table is filled with NULL.)Equi-join and Non-equi-joinSelf-join
*/
-- Joined table query join --
-- Query the student number, name, score, and subject number of students who took the exam.
/*Approach
1. Analyze the approach, determining which tables each required field comes from,
2. Determine which type of join query to use (the result of querying individual tables should form a complete table for the requirement): 7 types
-> Determine the intersection point (which data is the same in these two tables)
The condition: based on the same field name in both tables, such as: studentNo in the student table = studentNo in the result table
*/
-- JOIN + the table to connect + ON + the condition to judge  (A specific syntax for join query)
-- WHERE		Equi-join

4.4.3.1. In this example, the results of INNER JOIN and RIGHT JOIN are the same

-- INNER JOIN
SELECT s.studentNo, studentName, SubjectNo, StudentResult	-- The field names at the intersection must declare which table they come from
FROM student AS s
INNER JOIN result AS r
WHERE s.studentNo = r.studentNo	-- on is the condition before joining the tables, where is the filter after joining the tables
-- RIGHT JOIN, with the fields from the right table as the basis
SELECT s.studentNo, studentName, SubjectNo, StudentResult
FROM student AS s	-- Left table
RIGHT JOIN result AS r	-- Right table
ON s.studentNo = r.studentNo

Insert image description here

4.4.3.2.LEFT JOIN

-- LEFT JOIN, with the fields of the left table prevailing 
-- Difference from a right join: shows information about people without test scores
SELECT s.studentNo, studentName, SubjectNo, StudentResult
FROM student AS s -- right table
LEFT JOIN result AS r -- left table
ON s.studentNo = r.studentNo

在这里插入图片描述

4.4.3.3. querying students who missed exams

-- Query the students who missed the exam
SELECT s.studentNo, studentName, SubjectNo, StudentResult
FROM student s -- right table
LEFT JOIN result r -- left table
ON s.studentNo = r.studentNo
WHERE StudentResult IS NULL

在这里插入图片描述

4.4.3.4. Exercise: Query Information of Students Who Took Exams (Student ID, Student Name, Subject Name, Score)

-- Exercise: Query information of students who took exams (student ID, student name, subject name, score)
/*Approach
1. Analyze the approach, determining which tables each required field comes from: student, result, subject join query.
2. Determine which type of join query to use (the result of querying individual tables should form a complete table for the requirement): 7 types
-> Determine the intersection point (which data is the same in these two tables)
The condition: based on the same field name in both tables, such as: studentNo in the student table = studentNo in the result table
*/
-- Lines 10~11 (first connection point) from here is the left table join here is the right table choose which table to base on decides whether to use left or right
SELECT s.studentNo, studentName, subjectName, `StudentResult`
FROM student s
RIGHT JOIN result r
ON r.studentNo = s.studentNo
INNER JOIN `subject` sub
ON r.subjectNo = sub.subjectNo

Insert image description here

#Standard Thinking Steps
-- What data do I want to query -> SELECT ...
-- From which tables -> FROM some table JOIN the table to connect ON the intersection condition of these two tables
-- If querying from multiple tables, repeat the previous step, starting with connecting two tables

4.4.3.5. Self-Join (For Understanding)

A table joins itself, essentially splitting into two identical tables
  1. Parent category
    Insert image description here

  2. Subcategory
    Insert image description here

  3. Desired query result
    Insert image description here

#Self-Join
-- Write SQL statement to present the parent-child relationship of categories (Parent Category Name, Subcategory Name)
-- Query parent-child information: Split one table into two identical tables
SELECT a.`categoryName` AS 'Parent Category', b.`categoryName` AS 'Subcategory'
FROM `category` AS a, `category` AS b
WHERE a.`categoryid` = b.`pid`

Insert image description here

Query the Grade of Students (Student ID, Name, Grade Name)
-- Query the grade of students (student ID, name, grade name)
SELECT studentNo, studentName, `GradeName`
FROM student s
INNER JOIN `grade` g
ON s.`GradeID` = g.`GradeID`

Insert image description here

Query the Grade of Subjects (Subject Name, Grade Name)
-- Query the grade of subjects (subject name, grade name)
SELECT `SubjectName`,`GradeName`
FROM `subject` sub
INNER JOIN `grade` g
ON sub.`GradeID` = g.`GradeID`

Insert image description here

Query Information of Students Who Took ‘Advanced Mathematics-1’ Exam (Student ID, Student Name, Subject Name, Score)
-- Query information of students who took the 'Advanced Mathematics-1' exam (student ID, student name, subject name, score)
SELECT s.`StudentNo`, `StudentName`, `SubjectName`, `StudentResult`
FROM student s
INNER JOIN `result` r
ON s.StudentNo = r.StudentNo
INNER JOIN `subject` sub
ON r.`SubjectNo` = sub.`SubjectNo`
WHERE subjectName = 'Advanced Mathematics-1'

Insert image description here

4.5. Sorting and Pagination

4.5.1. Sorting

4.5.1.1. ORDER BY: Which field to sort by and how

Syntax: ORDER BYThe ORDER BY statement is used to sort the result set by a specified column.The ORDER BY statement defaults to sorting records in ascending order (ASC).To sort the records in descending order, you can use the DESC keyword.
-- Pagination with limit and sorting with order by --
#Sorting: ASC for ascending, DESC for descending
#Syntax: ORDER BY which field to sort by and how
SELECT s.`StudentNo`, `StudentName`, `SubjectName`, `StudentResult`
FROM student s
INNER JOIN `result` r
ON s.StudentNo = r.StudentNo
INNER JOIN `subject` sub
ON r.`SubjectNo` = sub.`SubjectNo`
WHERE subjectName = 'Advanced Mathematics-1'
ORDER BY StudentResult DESC	-- The results are sorted in 'descending' order by score
-- To sort the results in 'ascending' order by score, simply change DESC to ASC

Insert image description here
Insert image description here

4.5.2. Pagination

Syntax: SELECT * FROM table LIMIT [offset (number of pages to skip),] rows (how many rows per page) | rows OFFSET offset
Benefits: (User experience, Network transmission, Query pressure)

4.5.2.1. Displaying data skipping the top five scores in descending order

#Pagination
/*
First page: LIMIT 0,5 (skip 0 rows, 5 rows on this page)
Second page: LIMIT 5,5 (skip 5 rows, 5 rows on this page)
Third page: LIMIT 10,5 (skip 10 rows, 5 rows on this page)
......
Nth page: LIMIT (pageNo - 1) * pageSize, pageSizewhere pageNo is the page number, pageSize is the number of items per page, total pages = |_Total Items / Items per Page_|
*/
-- Displaying data skipping the top five scores in descending order
SELECT s.`StudentNo`, `StudentName`, `SubjectName`, `StudentResult`
FROM student s
INNER JOIN `result` r
ON s.StudentNo = r.StudentNo
INNER JOIN `subject` sub
ON r.`SubjectNo` = sub.`SubjectNo`
WHERE subjectName = 'Advanced Mathematics-1'
ORDER BY StudentResult DESC, StudentNo
LIMIT 1,5

Insert image description here

4.5.2.2. Query the top 10 students by score in ‘Advanced Mathematics-3’, with scores no less than 80 (Student ID, Name, Course Name, Score)

-- Query the top 10 students by score in 'Advanced Mathematics-3', with scores no less than 80 (Student ID, Name, Course Name, Score)
SELECT s.`StudentNo`, `StudentName`, `SubjectName`, `StudentResult`
FROM `student` s
INNER JOIN `result` r
ON s.StudentNo = r.StudentNo
INNER JOIN `subject` sub
ON r.`SubjectNo` = sub.`SubjectNo`
WHERE subjectName = 'Advanced Mathematics-3' AND StudentResult >= 80
ORDER BY StudentResult DESC, StudentNo
LIMIT 0,10

Insert image description here

4.6. Subqueries

4.6.1. Query all exam results for ‘Advanced Mathematics-3’ (Student ID, Course Number, Score) in descending order

4.6.2.1. Method 1: Using join queries + subqueries

-- Subqueries --
-- 1. Query all exam results for 'Advanced Mathematics-3' (Student ID, Course Number, Score) in descending order
#Method 1: Using join queries
SELECT `StudentNo`, sub.`SubjectNo`, `StudentResult`	-- or r.SubjectNo is also possible
FROM `result` r
INNER JOIN `subject` sub
ON r.SubjectNo = sub.SubjectNo
WHERE SubjectName = 'Advanced Mathematics-3'
ORDER BY StudentResult DESC

4.6.1.2. Method 2: Using subqueries (Inside-out approach)

#Method 2: Using subqueries (Inside-out approach)
SELECT `StudentNo`, `SubjectNo`, `StudentResult`
FROM `result`
WHERE SubjectNo = (SELECT SubjectNo FROM `subject`WHERE SubjectName = 'Advanced Mathematics-3'
)
ORDER BY StudentResult DESC

Insert image description here

4.6.2. Query student ID and name for students scoring above 80 in ‘Advanced Mathematics-4’

4.6.2.1. Method 1: Using join queries + subqueries

-- 2. Query student ID and name for students scoring above 80 in 'Advanced Mathematics-4'
#Method 1: Using join queries + subqueries
-- First part: Getting student IDs and names for students scoring above 80 in any subject
SELECT DISTINCT s.`StudentNo`, `StudentName`	-- Without DISTINCT, each matching result appears (the same person's name and ID may appear multiple times)
FROM student s
INNER JOIN result r
ON r.StudentNo = s.StudentNo	-- Up to this point, it includes students with scores in any subject
WHERE `StudentResult` > 80
-- Second part: Adding 'Advanced Mathematics-4' on this basis, avoiding another join query -> switching to querying the course number
SELECT DISTINCT s.`StudentNo`, `StudentName`
FROM student s
INNER JOIN result r
ON r.StudentNo = s.StudentNo
WHERE `StudentResult` > 80 AND `SubjectNo` = (SELECT SubjectNoFROM `subject`WHERE `SubjectName` = 'Advanced Mathematics-4'
)

4.6.2.2. Method 2: Using Join Queries

#Method 2: Using Join Queries
SELECT DISTINCT s.`StudentNo`, `StudentName`
FROM student s
INNER JOIN result r
ON r.StudentNo = s.StudentNo
INNER JOIN `subject` sub
ON r.SubjectNo = sub.SubjectNo
WHERE `StudentResult` > 80 AND SubjectName = 'Advanced Mathematics-4'

4.6.2.3. Method 3: Using Subqueries

#Method 3: Using Subqueries
SELECT StudentNo, StudentName FROM student WHERE StudentNo IN (		-- It's better to use equals (=) instead of IN for a single condition, as = is more efficient in queries.SELECT StudentNo FROM result WHERE StudentResult > 80 AND SubjectNo = (SELECT SubjectNo FROM `subject` WHERE `SubjectName` = 'Advanced Mathematics-4')
)

Insert image description here

4.6.3. Exercises

4.6.3.1. Query the top 5 students’ scores in C Language-1 (Student ID, Name, Score)

/*
Exercise:Query the top 5 students' scores in C Language-1 (Student ID, Name, Score).Use a subquery to find the grade name where student Liu Fu is enrolled.
*/
-- 1
SELECT s.StudentNo, StudentName, StudentResult 
FROM student s
INNER JOIN result r
ON s.StudentNo = r.StudentNo
WHERE SubjectNo = (SELECT SubjectNo FROM `subject` WHERE SubjectName = 'C Language-1'
)
ORDER BY StudentResult DESC
LIMIT 0,5

Insert image description here

4.6.3.2. Using a subquery, find the grade name where student Liu Fu is enrolled

-- 2
SELECT GradeName FROM grade WHERE GradeID = (SELECT GradeID FROM student WHERE StudentName = 'Liu Fu'
)

Insert image description here

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/589092.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何使用VNC+Cpolar实现Windows电脑公网远程控制Ubuntu系统桌面

文章目录 前言1. VisualSVN安装与配置2. VisualSVN Server管理界面配置3. 安装cpolar内网穿透3.1 注册账号3.2 下载cpolar客户端3.3 登录cpolar web ui管理界面3.4 创建公网地址 4. 固定公网地址访问 前言 SVN 是 subversion 的缩写,是一个开放源代码的版本控制系统…

Java就近原则和this关键字

Java 中的就近原则和 this 关键字有着密切的关系,特别是在处理成员变量与方法参数同名的情况下。就近原则指的是在同一作用域下,优先使用最近声明的变量或参数。 在 Java 中,如果一个方法的参数与类的成员变量同名,为了明确指示要…

Hadoop和zookeeper集群相关执行脚本(未完,持续更新中~)

1、Hadoop集群查看状态 搭建Hadoop数据集群时,按以下路径操作即可生成脚本 [test_1analysis01 bin]$ pwd /home/test_1/hadoop/bin [test_01analysis01 bin]$ vim jpsall #!/bin/bash for host in analysis01 analysis02 analysis03 do echo $host s…

2013年认证杯SPSSPRO杯数学建模B题(第二阶段)流行音乐发展简史全过程文档及程序

2013年认证杯SPSSPRO杯数学建模 B题 流行音乐发展简史 原题再现: 随着互联网的发展,流行音乐的主要传播媒介从传统的电台和唱片逐渐过渡到网络下载和网络电台等。网络电台需要根据收听者的已知喜好,自动推荐并播放其它音乐。由于每个人喜好…

马化腾的电商梦,只能靠它来实现了~

我是王路飞。 腾讯要开始加大对电商的投入力度了, 而这些资源所依托的载体,正是【视频号】。 在2023微信公开课PRO上,视频号团队介绍,2022年总用户使用时长已经超过了朋友圈总用户使用时长的80%。视频号直播的看播时长增长156%…

使用OpenCV4.9的随机生成器和文本

返回:OpenCV系列文章目录(持续更新中......) 上一篇:OpenCV 4.9基本绘图 下一篇:OpenCV系列文章目录(持续更新中......) 目标 在本教程中,您将学习如何: 使用随机数生…

C++ 11是如何封装Thread库的?

引言 C11 标准引入了一个重要的特性,即原生线程支持,这标志着C语言在并发编程领域迈出了坚实的步伐。在此之前,开发人员在进行跨平台的多线程编程时,不得不依赖于操作系统提供的特定API,如Windows API或POSIX Threads…

33-SDK设计(上):如何设计出一个优秀的GoSDK?

在实际的项目开发中,通常会提供对开发者更友好的SDK包,供客户端调用。很多大型服务在发布时都会伴随着SDK的发布,例如腾讯云很多产品都提供了SDK: 什么是SDK? 对于SDK(Software Development Kit&#xff0c…

GBK文件批量转UTF-8,python脚本

import os import codecsdef convert_encoding(file_path):try:# 尝试以gb18030编码打开文件并读取内容with codecs.open(file_path, r, gb18030) as f:content f.read()except UnicodeDecodeError:# 如果出现解码错误,尝试使用utf-8编码打开文件with codecs.open(…

【数据结构与算法】二叉搜索树和平衡二叉树

二叉搜索树 左子树的结点都比当前结点小,右子树的结点都比当前结点大。 构造二叉搜索树: let arr [3, 4, 7, 5, 2]function Node(value) {this.value valuethis.left nullthis.right null }/*** 添加结点* param root 当前结点* param num 新的结…

SpringBoot 登录认证(二)Cookie与Sesstion

SpringBoot 登录认证(一)-CSDN博客 SpringBoot 登录认证(二)-CSDN博客 SpringBoot登录校验(三)-CSDN博客 HTTP是无状态协议 HTTP协议是无状态协议。什么又是无状态的协议? 所谓无状态&…

有Digicert免费证书吗

说到Digiert证书,DigiCert 是美国CA认证可信,提供了很过十年的SSL证书和SSL管理工具。与其他CA不同,DigiCert 完全专注于SSL的创新,提供完整系列的SSL证书、工具和管理平台。它是名副其实的行业单位。 “DigiCert”是这个行业中根…