DQL之多表查询
一,子查询
示例1:查询零库存商品
语句:select goodsname from goods where barcode in (select barcode from storesum where remained =0);
示例2:查询选修英语课程的学生人数
语句:select count(s_id) from score where s_id =(select c_id from course where c_name='英语');
示例3:查询三门课程都及格的同学的学号
语句:select s_id,s_score from score where s_id in (select s_id from score group by s_id having count(*)>2 and min(s_score)>=60);
示例4:查询选修数学的学生的学号和姓名
select s_id,s_name from student where s_id in (select s_id from score where c_id in (select c_id from course where c_name='数学'));
二,联接查询
(内联接):select * from student inner join score on student.s_id=score.s_id;
(左联接):select * from student left join score on student.s_id=score.s_id;
(右联接):select * from student right join score on student.s_id=score.s_id;
示例1:查询选修课程的学生姓名和学号
语句:select s_name from student inner join score on student.s_id=score.s_id;
示例2:查询选修数学的学生的学号和姓名
语句:
select s.s_id,s.s_name from student s inner join score sc on s.s_id=sc.s_id inner join course c on sc.c_id =c.c_id where c.c_name ='数学';
示例3:查询三门课程都及格的同学的学号
语句:
select * from student s inner join score sc on s.s_id =sc.s_id and sc.score>=60 group by s.s_id having count(*)>2;