mysql自连接查询

本文介绍了如何通过SQL查询获取数学成绩最高的学生详细信息,并同时得到该学生的班长姓名。首先展示了学生和班级的数据库表结构,然后提出了问题——查询数学成绩最高的学生及其班长姓名。解决方案是通过两次连接操作实现,首先学生表与班级表内连接获取班长学号,再利用班长学号与学生表自连接获取班长姓名。最后给出了具体的SQL查询语句。
摘要由CSDN通过智能技术生成

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)

在这里插入图片描述

今天群里看到的问题,我就帮别人解答了,对自己也是一种进步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别团等shy哥发育

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值