-- 如果多张表进行连接的时候,第一种使用多个join……on……即可
-- 第二种使用and将所有条件连接起来即可
select 字段 from 表1 别名1 [inner] join 表2 别名2 on 连接条件 and 其他条件;
select 字段 from 表1 别名1,表2 别名2 where 连接条件 and 其他条件;
-- 查询所有班级所有课程的平均分
select
c.id c_id,
c.name c_name,
cou.name cou_name,
avg(e.score)
from student s, classes c, exam_score e, course cou
where s.classes_id=c.id
and s.id=e.student_id
and e.course_id=cou.id
group by c.id, cou.id;
-- 也可以使用 join on的写法
select
c.id c_id,
c.name c_name,
cou.name cou_name,
avg(e.score)
from student s
join classes c on s.classes_id=c.id
join exam_score e on s.id=e.student_id
join course cou on e.course_id=cou.id
group by c.id, cou.id;
(2)外连接
外连接分为左外连接和右外连接。左外连接的左表和右外连接的右表我们称之为外表,外表会被完全显示。
-- 左外连接,表1完全显示
select 字段名 from 表名1 left join 表名2 on 连接条件 where 其他条件;
-- 右外连接,表2完全显示
select 字段 from 表名1 right join 表名2 on 连接条件 where 其他条件;
-- 使用自连接,第一张表保存语文成绩,第二张表保存数学成绩,进行筛选即可
select
*
from exam_score e1,exam_score e2
where e1.student_id=e2.student_id
and e1.course_id=1
and e2.course_id=2
and e1.score>e2.score;
(4)子查询
子查询是指嵌入到其它sql语句中的select语句,也叫嵌套查询。
单行子查询(做为常量):返回一行一列数据
例:查询‘张三’的同班同学
select * from student where classes_id=(select classes_id from student where
name='张三');