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 '班长学号'
);
class表
student表
问题:查询数学成绩最高的学生信息和该学生班长的姓名
想法:想要获取班长的学号必须将学生表和班级表做一次内连接,但这样只能拿到学号,拿不到班长的姓名,所以用班长的学号再和学生表做一次自连接即可
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)
今天群里看到的问题,我就帮别人解答了,对自己也是一种进步