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 Name | Description |
---|---|
INNER JOIN | Returns rows if there is at least one match in the tables |
LEFT JOIN | Returns all rows from the left table, even if there are no matches in the right table |
RIGHT JOIN | Returns all rows from the right table, even if there are no matches in the left table |
4.4.2. Seven Types of JOINs
4.4.3. Examples
/*
Join Queries
To query data from multiple tables, connection operators can be used to perform multiple queries.
Inner join
Queries the intersection of the result sets of two tables.
Outer join
Left 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-join
Self-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
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
#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
-
Parent category
-
Subcategory
-
Desired query result
#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`
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`
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`
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'
4.5. Sorting and Pagination
4.5.1. Sorting
4.5.1.1. ORDER BY: Which field to sort by and how
Syntax: ORDER BY
The 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
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, pageSize
where 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
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
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
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 SubjectNo
FROM `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'
)
)
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
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'
)