查询所有课程成绩都大于90分的学生:

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stu_name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `course` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `score` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
INSERT INTO student (id, stu_name, course, score)VALUES (1, '李强', '语文', 95);

INSERT INTO student (id, stu_name, course, score)VALUES (2, '李强', '数学', 90);

INSERT INTO student (id, stu_name, course, score)VALUES (3, '李强', '英语', 92);

INSERT INTO student (id, stu_name, course, score)VALUES (4, '王辉', '语文', 94);

INSERT INTO student (id, stu_name, course, score)VALUES (5, '王辉', '政治', 93);

INSERT INTO student (id, stu_name, course, score)VALUES (6, '张三', '政治', 96);

INSERT INTO student (id, stu_name, course, score)VALUES (7, '李四', '体育', 88);

在这里插入图片描述
这里,只有张三、王辉满足条件。

1、group by + 聚合函数

按学生分组,按学生的最小分数聚合:

select stu_name from student group by stu_name having min(score) > 90 

2、not in + 子查询

先查询有得分小于等于90分的学生姓名,再排除这部分姓名:

select distinct  stu_name from student where stu_name not in (

select distinct stu_name from student where score <= 90

)

3、连接查询

左连接 存在得分小于等于90的学生姓名,抛弃匹配上的:

select distinct a.stu_name from student  a 

left join (select distinct stu_name from student where score <= 90)  b  on a.stu_name = b.stu_name 

where b.stu_name is null

4、not exist

查询没有存在一科成绩小于90的学生姓名:

select distinct a.stu_name from student  a where not exists 
(

select stu_name from student  where score <= 90 and stu_name = a.stu_name

)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐