“SQL 学生 课程 分数 2”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (→准备数据) |
Jihongchang(讨论 | 贡献) |
||
第37行: | 第37行: | ||
=== 查询只考了语文数学的学生,显示姓名,要求两种实现,并且其中一种要用到group by === | === 查询只考了语文数学的学生,显示姓名,要求两种实现,并且其中一种要用到group by === | ||
+ | <syntaxhighlight lang="sql"> | ||
+ | select s.id, s.name | ||
+ | from ( | ||
+ | select distinct student_id, course_id | ||
+ | from score | ||
+ | where course_id in (1,2) | ||
+ | ) sc left join student s | ||
+ | on sc.student_id = s.id | ||
+ | group by student_id having count(1) = 2; | ||
+ | </syntaxhighlight> | ||
=== 查询没有考完所有科目的学生 === | === 查询没有考完所有科目的学生 === |
2024年7月9日 (二) 05:13的版本
建表
create table course (
id integer primary key,
name text not null
);
create table student (
id integer primary key,
name text not null
);
create table score (
id integer primary key,
course_id integer not null,
student_id integer not null,
score integer not null
);
准备数据
insert into course values (1, '语文'), (2, '数学'),(3,'外语');
insert into student values (1, '小张'), (2, '小王'), (3, '小马'), (4, '小李');
#小张只考了语文
insert into score values (1, 1, 1, 80);
#小王考了语文和数学
insert into score values (4,1,2,70),(5,2,2,90);
#小马考了语文、数学、外语
insert into score values (7,1,3,80),(8,2,3,60),(9,3,3,70);
#小李考了语文、数学、外语,外语考了两次
insert into score values (10,1,4,80),(11,2,4,60),(12,3,4,70),(13,3,4,80);
查询只考了语文数学的学生,显示姓名,要求两种实现,并且其中一种要用到group by
select s.id, s.name
from (
select distinct student_id, course_id
from score
where course_id in (1,2)
) sc left join student s
on sc.student_id = s.id
group by student_id having count(1) = 2;