假设一个数据库有两个表:
+------+------+-------+
| sid | cid | score |
+------+------+-------+
| 01 | 01 | 80.0 |
| 01 | 02 | 90.0 |
| 01 | 03 | 99.0 |
| 02 | 01 | 70.0 |
| 02 | 02 | 60.0 |
| 02 | 03 | 80.0 |
| 03 | 01 | 80.0 |
| 03 | 02 | 80.0 |
| 03 | 03 | 80.0 |
| 04 | 01 | 50.0 |
| 04 | 02 | 30.0 |
| 04 | 03 | 20.0 |
| 05 | 01 | 76.0 |
| 05 | 02 | 87.0 |
| 06 | 01 | 31.0 |
| 06 | 03 | 34.0 |
| 07 | 02 | 89.0 |
| 07 | 03 | 98.0 |
+------+------+-------+
sid是学生ID,cid是课程ID,分数只是分数。
+-------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+-------+
| sid | varchar(10) | YES | | NULL | |
| cid | varchar(10) | YES | | NULL | |
| score | decimal(18,1) | YES | | NULL | |
+-------+---------------+------+-----+---------+-------+
+------+-------+---------------------+------+
| sid | sname | dob | ssex |
+------+-------+---------------------+------+
| 01 | Amy | 1990-01-01 00:00:00 | M |
| 02 | Bob | 1990-12-21 00:00:00 | M |
| 03 | Cath | 1990-05-20 00:00:00 | M |
| 04 | Dick | 1990-08-06 00:00:00 | M |
| 05 | Ella | 1991-12-01 00:00:00 | F |
| 06 | Geroge| 1992-03-01 00:00:00 | F |
| 07 | Froth | 1989-07-01 00:00:00 | F |
| 08 | Hue | 1990-01-20 00:00:00 | F |
+------+-------+---------------------+------+
使用
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid | varchar(10) | YES | | NULL | |
| sname | varchar(10) | YES | | NULL | |
| sage | datetime | YES | | NULL | |
| ssex | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
返回已注册完全相同课程的学生的sid和sname sid为'01'的学生?
例如,从SC表中,我们可以看到sid'01'的学生注册了课程01,02,03。 sid 02,03,04也注册相同的课程。 因此,我们需要返回
+------+-------+
| sid | sname |
+------+-------+
| 02 | Bob |
| 03 | Cath |
| 04 | Dick |
+------+-------+
我不知道该怎么做,我不确定是否存在一些优雅的解决方案,例如:
SELECT sid, sname from student
where sid in
( select distinct sid from SC
group by sid
having cid = (select distinct cid from SC where sid = '01')
);
有可能这样做吗?
答案 0 :(得分:0)
使用此查询:
select sid from sc
group by sid
having
sum(cid in (select cid from sc where sid = '01')) =
(select count(*) from sc where sid = '01')
and
sum(cid not in (select cid from sc where sid = '01')) = 0
您将获得符合您条件的所有学生的ID。
然后将其连接到表student
:
select s.sid, s.sname
from student s inner join (
select sid from sc
group by sid
having
sum(cid in (select cid from sc where sid = '01')) =
(select count(*) from sc where sid = '01')
and
sum(cid not in (select cid from sc where sid = '01')) = 0
) g on g.sid = s.sid
where s.sid <> '01'