几种连接
-
内链接 (inner) 两张表公共的部分集合在一起(取交集),产生的结果集
-
全外连接 (full outer) 所有在A表和B表中存在的数据。无法对应Null填充 只存在于A表或B表中的数据,过滤两个表公共的部分
- 左外连接 (left outer) A表和B表,以左表为基础, 只存在A表且不存在B表中的结果
- 右外连接 (right outer) 以右表为基础,(保留B的数据)
- 交叉连接 (cross) 如果A和B是两个集合,交叉连接就是AxB
连接查询
对有关系的多张表进行查询,使用连接join
区别:结果集不一样
select students.name,subjects.title,scores.score
from scores
inner join students on scores.stuid=students.id
inner join subjects on scores.subid=subjects.id;
查询男生的姓名/总分
建立连接: students.id=sccores.stuid
使用sum-->分组, 姓名:每个人的总分
select name,sum(score) from students
inner join scores on
students.id=scores.stuid
where students.gender=1
group by students.name;
查询科目的名称/ 平均分
select subjects.title,avg(scores.score) from scores
inner join subjects on
scores.subid=subjects.id
group by subjects.title;
查询未删除科目的名称/最高分/平均分
select title,max(scores.score),avg(scores.score) from subjects
inner join scores on
subjects.id=scores.subid
where subjects.isDelete=0
group by subjects.title;