当前位置: 代码迷 >> 综合 >> 用一条SQL语句查询出每门课程的成绩都大于80的学生姓名
  详细解决方案

用一条SQL语句查询出每门课程的成绩都大于80的学生姓名

热度:48   发布时间:2023-10-12 00:56:19.0
-- 用一条SQL语句查询出每门课程的成绩都大于80的学生姓名。Student表如下:
-- name  course	  score
-- 张三   语文		81
-- 张三	 数学		75
-- 李四	 语文		76
-- 李四	 数学		90
-- 王五	 语文		81
-- 王五	 数学 	   100
-- 王五	 英语		90create table test1(
id int auto_increment,
name varchar(10),
course varchar(10),
score int,
primary key pk_test1(id)
)engine=InnoDB,charset=utf8mb4;
insert into test1 values
(0,'张三','语文',81),(0,'张三','数学',75),
(0,'李四','语文',76),(0,'李四','数学',90),
(0,'王五','语文',81),(0,'王五','数学',100),
(0,'王五','英语',90);
select * from test1;
#这道题有两种理解思路:
#第一种是出现在表里面的课程就是该人的所有课程,即张三李四在没有英语成绩下,两门都大于80也是算每门都大于80。
#用not in 或者 not exists 实现 第一种的写法 不过DISTINCT关键字尽量少用,效率太低
-- not in 
select distinct name from test1 where name not in 
(select distinct name from test1 where score < 80);
-- not exists
select distinct name from test1 a where not exists 
(select name from test1 b where score < 80 and a.name=b.name);
-- 效率比较高
select name from test1 group by name having min(score) >= 80;
#第二种是他们都有英语数学语文三门课程,没有出现在表的成绩要按0来算,即张三李四还有一门成绩为0的英语。
-- 效率高的写法
select name from test1 group by name having count(1) = 3 and min(score) >= 80;

 

  相关解决方案