mysql中有关查询的技巧方法

* 查最高值或者最低值对应行的数据:

查询Score表中的最高分的学生学号和课程号:

两种方法(子查询或者排序):

子查询法:select sno,cno from score where degree = (select max(degree) from score);

分析:

1.查score表中的最高分 select max(degree) from score;

2.查最高分的学号跟课程号 select sno,cno from score where degree = 最高分查询语句;

排序法:select sno,cno from score order by degree desc limit 1;   //按照降序排列,取第一条最大的数据

 

 

* 查询Score表中至少有5名学生选修的并以3开头的课程的平均分数:(‘至少’,‘至多’问题)

方法一:select avg(degree) from score where cno like '3%' group by cno having count(*)>=5;

分析:

1.以3开头的课程 cno like "3%"

2.学生选修=》以选修课为组 group by cno having count(sno)>=5

方法二:select avg(degree) from score where cno like '3%' and cno in (select cno from score group by cno having count(sno)>=5);

 

* 查询至少两名男生的班号

方法一:select class from student where ssex='男' group by class having(ssex)>=2;

方法二:select class from student where ssex='男' and ssex in (select ssex from score group by class having(ssex)>=2);

 

* 查询成绩比课程平均成绩低的同学的成绩表(特殊链接,关键字 ‘该’)

思路:

1.查询成绩  select degree from score a where degree<'子查询中的平均成绩';

2.子查询平均成绩  select avg(degree) from score b where b.cno=a.cno; 此表中的课程与父表中的课程一致(必要条件)

3.衔接 select degree from score a where degree<(select avg(degree) from score b where b.cno=a.cno);

原文地址:https://www.cnblogs.com/laoniaofly/p/8405694.html