问:查询每一个学生每一个科目的分数ui
分析:学生姓名来源于students表,科目名称来源于subjects,分数来源于scores表,怎么将3个表放到一块儿查询,并将结果显示在同一个结果集中呢?spa
答:当查询结果来源于多张表时,须要使用链接查询code
关键:找到表间的关系,当前的关系是blog
则上面问题的答案是: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
链接查询分类以下:select
在查询或条件中推荐使用“表名.列名”的语法语法
若是多个表中列名不重复能够省略“表名.”部分数据
若是表的名称太长,能够在表名后面使用' as 简写名'或' 简写名',为表起个临时的简写名称查询
select students.sname,avg(scores.score) from scores inner join students on scores.stuid=students.id group by students.sname;
select students.sname,avg(scores.score) from scores inner join students on scores.stuid=students.id where students.gender=1 group by students.sname;
select subjects.stitle,avg(scores.score) from scores inner join subjects on scores.subid=subjects.id group by subjects.stitle;
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;