数据库连接
主机地址:rm-bp188nr95fk4l9545ao.mysql.rds.aliyuncs.com
端口号:3306
用户名:abtester
密码:123@abtester
子查询
- 查询年龄最大的学生有哪些?
解决的思路:
a. 出生日期越小,年龄越大—》 找出 birthdate 出生年月最小的人有哪些。 需要使用到min()
select min(birthdate) from students;
b.根据值找对应的人;
select * from students WHERE
-- 先找到出生年月最小的数据
birthdate = (select min(birthdate) from students) ;
- 查询年龄第二大的学生有哪些?
a. 先找到出生日期,找到生成日期第二小。 —> 去重,排序
去重有两种, group by, distinct
select distinct(birthdate) from students
order by birthdate
limit 1,1;
b. 根据对应的日期找到对应的人。
-- 根据birtdate 值来找人;
select * from students WHERE
birthdate = (select distinct(birthdate) from students
order by birthdate
limit 1,1);
多表查询
查询每个同学的各科成绩,显示学号,学生姓名,科目,成绩;
select students.sno, sname,cname,score from students
inner join score
on students.sno = score.sno
inner join course
on score.cno = course.cno;
查询总分最高的同学,显示学号,姓名,总成绩;
a. 先找到总分最高的分数是多少;
可以在 成绩表中通过 sum() 求总和; 排序取第一;
select sno,sum(score) from score
group by sno;
b. 根据最高分找人;
-- 1 找到最高分数
select sum(score) from score
group by sno
ORDER BY sum(score) DESC
LIMIT 1;
-- 2 根据分数找打对应的学号
select sno, sum(score) 总成绩 from score
GROUP BY sno HAVING sum(score) =
(select sum(score) from score
group by sno
ORDER BY sum(score) DESC
LIMIT 1)
-- 3. 根据学号找到对应的人
SELECT students.sno, students.sname, 总成绩 FROM students
INNER JOIN (select sno, sum(score) 总成绩 from score
GROUP BY sno HAVING sum(score) =
(select sum(score) from score
group by sno
ORDER BY sum(score) DESC
LIMIT 1)) as tmp
ON tmp.sno = students.sno;