MySQL——联表查询JoinON详解

Join 对比(7种)


代码演示:

sql 复制代码
-- 查询参加了考试的同学(学号,姓名,科目编号,分数)
SELECT * FROM student
SELECT * FROM result

/*
1. 分析需求:分析查询的字段来自哪些表(超过一张表就要使用连接查询)
2. 确定使用哪种连接查询  共7种
3. 确定交叉点(这两个表中哪个数据是相同的)
4. 判断的条件:学生表中的 studentno = 成绩表 studentno
*/

SELECT s.studentno,studentname,subjectno,studentresult
FROM student AS s
INNER JOIN result AS r
WHERE s.studentno = r.studentno


-- LEFT JOIN
SELECT s.studentno,studentname,subjectno,studentresult
FROM student s
LEFT JOIN result r
ON s.studentno = r.studentno


-- RIGHT JOIN
SELECT s.studentno,studentname,subjectno,studentresult
FROM student s
RIGHT JOIN result r
ON s.studentno = r.studentno

|------------|------------------------|
| 操作 | 描述 |
| Inner join | 如果表中至少有一个匹配,就返回行 |
| left join | 即使右表中没有匹配,也会从左表中返回所有的值 |
| right join | 即使左表中没有匹配,也会从右表中返回所有的值 |

sql 复制代码
-- 查询缺考的同学
SELECT s.studentno,studentname,subjectno,studentresult
FROM student s
LEFT JOIN result r
ON s.studentno = r.studentno
WHERE studentresult IS NULL
sql 复制代码
-- 思考题:查询参加考试的同学信息(学号,学生姓名,科目名,分数)
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

-- 若要在多张表查询,可以慢慢来,先查询两张表然后再增加
相关推荐
7***684314 小时前
Spring Boot 从 2.7.x 升级到 3.3注意事项
数据库·hive·spring boot
('-')14 小时前
《从根上理解MySQL是怎样运行的》第十章学习笔记
笔记·学习·mysql
L***d67014 小时前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot
java_logo14 小时前
MySQL Server Docker 容器化部署指南
linux·运维·数据库·docker·容器
likuolei14 小时前
XSL-FO 软件
java·开发语言·前端·数据库
p***950014 小时前
Springboot3 Mybatis-plus 3.5.9
数据库·oracle·mybatis
CS_浮鱼14 小时前
【MySQL】InnoDB存储引擎
数据库·mysql
合作小小程序员小小店14 小时前
桌面开发,在线%信息管理%系统,基于vs2022,c#,winform,sql server数据。
开发语言·数据库·sql·microsoft·c#
q***188414 小时前
解决phpstudy无法启动MySQL服务
数据库·mysql·adb
e***956414 小时前
【HTML+CSS】使用HTML与后端技术连接数据库
css·数据库·html