MySQL高级之链接

1、问题

问:查询每一个学生每一个科目的分数ui

分析:学生姓名来源于students表,科目名称来源于subjects,分数来源于scores表,怎么将3个表放到一块儿查询,并将结果显示在同一个结果集中呢?spa

答:当查询结果来源于多张表时,须要使用链接查询code

关键:找到表间的关系,当前的关系是blog

  • students表的id---scores表的stuid
  • subjects表的id---scores表的subid

则上面问题的答案是:it

select students.sname,subjects.stitle,scores.score
from scores
inner join students on scores.stuid=students.id
inner join subjects on scores.subid=subjects.id;

结论:当须要对有关系的多张表进行查询时,须要使用链接joinclass

2、链接查询

链接查询分类以下:select

  • 表A inner join 表B:表A与表B匹配的行会出如今结果中
  • 表A left join 表B:表A与表B匹配的行会出如今结果中,外加表A中独有的数据,未对应的数据使用null填充
  • 表A right join 表B:表A与表B匹配的行会出如今结果中,外加表B中独有的数据,未对应的数据使用null填充

在查询或条件中推荐使用“表名.列名”的语法语法

若是多个表中列名不重复能够省略“表名.”部分数据

若是表的名称太长,能够在表名后面使用' as 简写名'或' 简写名',为表起个临时的简写名称查询

3、练习

3.1 查询学生的姓名、平均分 

select students.sname,avg(scores.score)
from scores
inner join students on scores.stuid=students.id
group by students.sname;

3.2 查询男生的姓名、总分 

select students.sname,avg(scores.score)
from scores
inner join students on scores.stuid=students.id
where students.gender=1
group by students.sname; 

3.3 查询科目的名称、平均分

select subjects.stitle,avg(scores.score) from scores inner join subjects on scores.subid=subjects.id group by subjects.stitle;

3.4 查询未删除科目的名称、最高分、平均分

select subjects.stitle,avg(scores.score),max(scores.score)
from scores
inner join subjects on scores.subid=subjects.id
where subjects.isdelete=0
group by subjects.stitle;
相关文章
相关标签/搜索