1.drop,delete,truncate区别
1>delete删除过程是每次从表中删除一行记录,删除操作作为事务记录在日志中,必要时候可以进行回滚操作;truncate一次性清空表的所有数据,并且删除操作不会记在日志中,删除是不能恢复的,在删除过程中不会激活与表有关的触发器,执行速度快;
2>表和索引的空间:truncate后,表的索引和占用的空间恢复到初始的大小;delete操作不会减少表和索引所占的空间;drop将表占用的空间全部释放;
3>truncate只能操作table,不能操作view;而delete可以删除table和view;drop删除表的结构,包括约束,触发器以及索引;
2.having、group by关键字
1>.group by一般和聚合函数( COUNT, SUM, AVG, MIN, or MAX)一起使用,来得到某一列或者多列聚合结果;语法如下:
select column1,column2,aggregage_function(expression)
from tables
where predicates
group by column1,column2.....column_n;
比如,学生表(student),字段:学号(id),课程(course),分数(scrore)等多个列,要统计每个学生选了几门课程,可以使用count聚合函数与groupBy一起使用
select id,count(course) as numcourse
from student
group by id
注:聚合函数作用与一组数据返回一个值,因此无法,在select语句中的只能是聚合函数的值或者groupby的参数,不能是其他的列,否则会报错,例如
select id,count(course) as numcourse,score
from student
group by id
查询会出错,提示
Column ‘student.score' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
因为一个学号对应多个分数,无法确定哪一个;
2>having关键字,过滤group by语句的返回的记录集;语法
select column1,column2,aggregate_function(expression)
from tables
where predicates
group by clumn1,column2
having condition1...
比如,查询平均分大于80分的学生
select id,count(course) as numcourse,avg(score) as avg
from student
group by id
having avg(score)>80
注意having过滤的是每个记录集的聚合结果,where过滤的记录的行的值,二者是不同的,有时候,需要两者一起使用;例如要查询大于70分的学生成绩中平均分大于80分的
select id,avg(score)
from student
where score >70
group by id
having avg(score)>80
where 先过滤,之后对过滤结果进行分组;having对分组结果进行过滤;