1:– 寻找选择了课程1的学生信息
– 1:查询出选择了课程1的学生信息,
– 条件是:课程id是1.可以得到student_id
select student_id from studentcourse
where course_id=1;
– 2:根据得到的student_id.来获取学生信息
– 条件是:学生id相同。要注意有多个学生对应student_id。用in
select student.* from student
where id in(select student_id from studentcourse
where course_id=1);
– 如果不添加id相同。
select student.* from student ,studentcourse
where course_id=1;
这个是因为
在第一步select id from student;里面有10个选择
然后在第二步 select student.* from student ,studentcourse
where course_id=1
其实是在执行
select student_id from studentcourse
where course_id=1;
最后一共得到了50个。就是说是把前面的student里面的10个取出来,然后再执行了后面选出来的5个满足的,变成了50个。
简单模式,因为第二步是获取id相同情形下的学生信息,所以我们可以同时从两个表里面一起查询。只要多加条件就好。
select student.* from student ,studentcourse
where student.id=studentcourse.student_id and course_id=1;
2: 查询出同时选择了课程1和课程2的学生信息
select student.* from student,studentcourse
where student.id=studentcourse.student_id and course_id=1
and exists
(select student.* from student,studentcourse
where student.id=studentcourse.student_id and course_id=2);
因为有主查询和子查询,所以第二步select student.* from student,studentcourse可以省略student更简洁点:
select student.* from student,studentcourse
where student.id=studentcourse.student_id and course_id=1
and exists
(select student.* from studentcourse
where student.id=studentcourse.student_id and course_id=2);
exists的区别在于。先从子查询中查询,如果子查询结果存在,就会显示出主查询中的所有数据。
select *
from student
where exists(select *from studentcourse
where course_id=1
and student.id = studentcourse.student_id
);
由于同时满足select *from studentcourse
where course_id=1
有5个。
在进行第一步的时候
会把第一个带进来,判断是否满足。以此进行,最后满足的是5个
第二个比第一个少了个条件
select *
from student
where course_id=1
);
由于没有了约束条件,就直接得到的是10个id相同的。
记住,这个是在student里面查询。上面的第一个题目里不加id是在两个里面查询
先开始查询select *
from student
有10行,
然后select *from studentcourse
where course_id=1
course_id=1 没有附加约束,就是个简单结果。所以
有结果,就把第一行显示出来,
然后再次开始查询select *
from student
有10行,
然后select *from studentcourse
where course_id=1
有结果,就把第二行显示出来,
因为在子查询中,id相同的有10个。所以把主查询select *
from student的信息全部都显示出来了。