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

news2024/11/26 2:28:10

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 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

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 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

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, 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

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 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'
	)
)

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.coloradmin.cn/o/1565503.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

DLL导出API注意事项

文章目录 问题原则示例一解决方案 示例二解决方法 参考 问题 在 windows 平台下,如果在动态库的接口中使用 std::string 或其它 std 容器,会导致崩溃或其它内存问题,所以一般要求动态库的接口必须是 C 语言实现。 原则 一个原则:…

LabVIEW专栏二、调用子VI

该节目标是创建带子vi,修改vi属性,测试可重入和不可重入的区别 一 、设置子VI 把VI封装成为子VI,可以帮助模块化程序,简化代码结构。 任何VI本身都可以成为别的VI的子VI。 1.1、设置输入输出端子 1、在前面板空白处&#xff0…

JavaScript中什么叫深拷贝?

在 JavaScript 中,深拷贝指的是创建一个新的对象,这个新的对象与原始对象完全独立,没有任何共享的属性或者数据,它们不共享同一块内存地址。深拷贝会复制原始对象的所有属性和嵌套对象的所有属性,包括嵌套对象中的属性…

Mybatis——查询数据

查询操作 根据用户id查询单条记录,在映射器接口(UserMapper)中定义如下方法: package org.example.mapper;import org.example.demo.User;import java.util.List;public interface UserMapper {//根据id查询UserUser selectUserById(Integer userId); …

使用 RisingWave、NATS JetStream 和 Superset 进行实时物联网监控

在物联网(IoT)背景下,处理实时数据会遇到一些特定的障碍,如边缘计算资源不足、网络条件限制、扩展性存在问题、设备间有多样性差异。要克服这些挑战,需要高效的边缘计算技术、强大的安全措施、标准化协议、可扩展的管理…

【升降自如】OLED升降透明屏,智能调节,打造个性化观影体验

OLED升降透明屏,作为科技领域的创新之作,以其升降自如、智能调节的特点,为用户带来了前所未有的个性化观影体验。 这款透明屏采用先进的OLED显示技术,不仅色彩鲜艳、对比度高,而且具备出色的透明性能。更值得一提的是&…

3D人脸扫描技术与数字人深度定制服务:赋能打造超写实3D数字分身

在数字时代,3D数字分身有着广泛的应用场景,在动画视频、广告宣传片、大型活动主持人、AI交互数字人等领域,发挥着重要的商业价值。其中,3D人脸扫描技术,推动了超写实3D数字分身的诞生。 公司案例 2023海心沙元宇宙音乐…

10_MVC

文章目录 JSON常用的JSON解析Jackson的常规使用指定日期格式 MVC设计模式MVC介绍前后端分离案例(开发与Json相关接口) 三层架构三层架构介绍 JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,是存…

[中级]软考_软件设计_计算机组成与体系结构_06_ 流水线技术

流水线技术 前言相关考试考点一:流水线执行时间概念流水线步骤解析参数计算案例解析:流水线计算第一问第二问 考点二:流水线吞吐率 前言 第一章比较重要的一种计算题型,经常考到,一般考试1 ~ 2分。 相关考试 流水线…

【智能算法】蜜獾算法(HBA)原理及实现

目录 1.背景2.算法原理2.1算法思想2.2算法过程 3.结果展示4.参考文献 1.背景 2021年,FA Hashim等人受到自然界中蜜獾狩猎行为启发,提出了蜜獾算法((Honey Badger Algorithm,HBA)。 2.算法原理 2.1算法思想 蜜獾以其…

文献速递:深度学习胰腺癌诊断--深度学习算法用于从疾病轨迹预测胰腺癌风险

文献速递:深度学习胰腺癌诊断--深度学习算法用于从疾病轨迹预测胰腺癌风险 麦田医学 美好事物中转站 2024-04-02 14:36 Title 题目 A deep learning algorithm to predict risk of pancreatic cancer from disease trajectories 深度学习算法用于从疾病轨迹预测…

WPF-基础及进阶扩展合集(持续更新)

目录 一、基础 1、GridSplitter分割线 2、x:static访问资源文件 3、wpf触发器 4、添加xaml资源文件 5、Convert转换器 6、多路绑定与多路转换器 二、进阶扩展 1、HierarchicalDataTemplate 2、XmlDataProvider从外部文件获取源 3、TextBox在CellTemplate中的焦点问题…

【LeetCode热题100】79. 单词搜索(回溯)

一.题目要求 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平…

揭秘代码安全:告别硬编码,灵活策略守护你的账户密码信息安全

前言 在编写代码时,为了遵循严格的安全规范,应避免硬编码任何敏感信息如账号凭证、密钥等直接出现在源代码中。相反,推荐采取安全措施,如使用环境变量、加密存储或安全凭据管理系统来间接引用和保护这类数据。如此一来&#xff0c…

使用 Docker 部署 Puter 云桌面系统

1)Puter 介绍 :::info GitHub:https://github.com/HeyPuter/puter ::: Puter 是一个先进的开源桌面环境,运行在浏览器中,旨在具备丰富的功能、异常快速和高度可扩展性。它可以用于构建远程桌面环境,也可以作为云存储服…

c++对象指针

对象指针在使用之前必须先进行初始化。可以让它指向一个已定义的对象,也可以用new运算符动态建立堆对象。 定义对象指针的格式为: 类名 *对象指针 &对象; //或者 类名 *对象指针 new 类名(参数); 用对象指针访问对象数据成员的格式为&#xff1a…

python很坐标报错ufunc ‘isfinite‘ not supported for the input types

python使用plt画图的时候,出错。 出错全文如下: Traceback (most recent call last): plt.show() return _get_backend_mod().show(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ __call__ manager.show(**kwar…

Node.js环境调用百度智能云(百度云)api鉴权认证三步走

方式一 :Postman脚本的方式生成v1版本的认证字符串 Postman脚本下载 下载Postman pre-request Script 设置 Authorization 示例脚本 方式二:在线签名工具生成 (试用于验证编程字符串签名是否有错误) 签名计算工具 https://cloud.baidu.com/signature/index.html …

深入核心招聘场景,用友大易帮助健合集团解决「渠道、效率、体验」三件事

自1999年成立以来,健合集团一直致力于婴幼儿营养与护理、成人自然健康营养与护理、以及宠物营养与护理三大核心领域。作为全球高端家庭营养及护理品牌的佼佼者,健合集团始终秉持「让人们更健康更快乐」的企业理念,这不仅体现在产品和服务上&a…

腾讯云(CVM)托管进行权限维持

前言 刚好看到一个师傅分享了一个阿里云ECS实战攻防,然后想到了同样利用腾讯云CVM的托管亦可实现在实战攻防中的权限维持。 简介 腾讯云自动化助手(TencentCloud Automation Tools,TAT)是一个原生运维部署工具,它可…