数据库连接

  1. 主机地址:rm-bp188nr95fk4l9545ao.mysql.rds.aliyuncs.com
  2. 端口号:3306
  3. 用户名:abtester
  4. 密码:123@abtester

子查询

image.png

  1. 查询年龄最大的学生有哪些?

解决的思路:
a. 出生日期越小,年龄越大—》 找出 birthdate 出生年月最小的人有哪些。 需要使用到min()

  1. select min(birthdate) from students;
  1. b.根据值找对应的人;
  1. select * from students WHERE
  2. -- 先找到出生年月最小的数据
  3. birthdate = (select min(birthdate) from students) ;
  1. 查询年龄第二大的学生有哪些?

a. 先找到出生日期,找到生成日期第二小。 —> 去重,排序
去重有两种, group by, distinct

  1. select distinct(birthdate) from students
  2. order by birthdate
  3. limit 1,1;
  1. b. 根据对应的日期找到对应的人。
  1. -- 根据birtdate 值来找人;
  2. select * from students WHERE
  3. birthdate = (select distinct(birthdate) from students
  4. order by birthdate
  5. limit 1,1);

多表查询

image.png

  1. 查询每个同学的各科成绩,显示学号,学生姓名,科目,成绩;

    1. select students.sno, sname,cname,score from students
    2. inner join score
    3. on students.sno = score.sno
    4. inner join course
    5. on score.cno = course.cno;
  2. 查询总分最高的同学,显示学号,姓名,总成绩;

a. 先找到总分最高的分数是多少;
可以在 成绩表中通过 sum() 求总和; 排序取第一;

  1. select sno,sum(score) from score
  2. group by sno;

b. 根据最高分找人;

  1. -- 1 找到最高分数
  2. select sum(score) from score
  3. group by sno
  4. ORDER BY sum(score) DESC
  5. LIMIT 1;
  6. -- 2 根据分数找打对应的学号
  7. select sno, sum(score) 总成绩 from score
  8. GROUP BY sno HAVING sum(score) =
  9. (select sum(score) from score
  10. group by sno
  11. ORDER BY sum(score) DESC
  12. LIMIT 1)
  13. -- 3. 根据学号找到对应的人
  14. SELECT students.sno, students.sname, 总成绩 FROM students
  15. INNER JOIN (select sno, sum(score) 总成绩 from score
  16. GROUP BY sno HAVING sum(score) =
  17. (select sum(score) from score
  18. group by sno
  19. ORDER BY sum(score) DESC
  20. LIMIT 1)) as tmp
  21. ON tmp.sno = students.sno;