mysql自连接查询
1、数据库表结构如下:
create table student(
id int(11) primary key not null auto_increment comment '学号',
name varchar(100),
gender varchar(100),
class_id int(11) not null,
birth_day date,
literal_degree int(11),
math_degree int(11),
CONSTRAINT fk_student_class_id foreign key(class_id) REFERENCES class(id)
);
create table class(
id int(11) primary key not null auto_increment,
name varchar(100),
supervisor_name varchar(100),
leader_id int(11) comment '班长学号'
);
2、测试数据
class表
student表
3、问题描述:
问题:查询数学成绩最高的学生信息和该学生班长的姓名
想法:想要获取班长的学号必须将学生表和班级表做一次内连接,但这样只能拿到学号,拿不到班长的姓名,所以用班长的学号再和学生表做一次自连接即可
select s1.id,s1.name,s1.gender,s1.class_id,s1.birth_day,s1.literal_degree,
s1.math_degree,c.leader_id,s2.name
from student s1,student s2,class c
where s1.class_id=c.id and s2.id=c.leader_id
and s1.math_degree=(select max(math_degree) from student)
今天群里看到的问题,我就帮别人解答了,对自己也是一种进步
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?