分组查询
对单列进行分组查询
select subject,count(*) from studentinfo group by subject;
使用HAVING的分组查询
select subject,AVG(score) from studentinfo group by subject having subject ='英语';
select subject,AVG(score) from studentinfo where subject='英语';
where的查询效率比having的查询效率高,因为使用where语句是针对整个查询结果集进行条件过滤,而使用having是针对分组后的查询结果集进行条件过滤的。在使用分组查询时,也可以在group by子句前面先使用where子句对查询结果进行过滤后,再对其分组,这样就能够提高分组查询效率。
对多列进行分组查询,在分组查询中使用order by(对查询结果进行排序)
select subject,teacher,avg(score) from studentinfo group by subject,teacher order by avg(score) desc;
解释:order by一定是放在最后
多表查询
等值连接
select name,subjectname from newstudentinfo,subjectinfo where newstudentinfo.subjectid=subjectinfo.id;
select newstudentinfo.name,subjectinfo.subjectname,teacherinfo.teachername from newstudentinfo,subjectinfo,teacherinfo where newstudentinfo.subjectid=subjectinfo.id and newstudentinfo.teacherid=teacherinfo.id;
笛卡尔积:针对多个表查询后产生的结果而定义的。它表示的这种特殊的查询结果是指,当多个表进行联合查询时不指定查询的条件。那么,不指定查询条件就意味着查询的是所有的表的全部内容。查询全部内容的数据集合是所有查询的数据表中所有列的和以及行的乘积。查询一个4行*5列的表和3行*2列的表,结果是12行*7列的结果集。
一定要避免这种无意义的查询。
左外连接:显示左表的全部记录
select newstudentinfo.name,subjectinfo.subjectname from newstudentinfo right outer join subjectinfo on newstudentinfo.subject=subjectinfo.id;
右外连接:显示右表的全部记录
select newstudentinfo.name,subjectinfo.subjectname from newstudentinfo right outer join subjectinfo on newstudentinfo.subjectid=subjectinfo.id;
內连接
合并查询
使用别名
对合并后的查询结果排序
限制组合查询结果的行数