MySQL 执行过程
select xx from xx where xx group by xx having xx ordey by xx limit xx
SELECT `name`,COUNT(`name`) AS num FROM student WHERE grade < 60 GROUP BY `name` HAVING num >= 2 ORDER BY num DESC,`name` ASC LIMIT 0,2;
主表结构:
过程:
1、执行where 条件语句 生成临时表
等价于执行:
select id ,name,subject,grade from student where grade < 60;
生成临时表a1的数据:
2、对生成的临时表a1进行分组操作
1)等价于:先将临时表a1按name进行分组查询,生成多个临时表
select id ,name,subject,grade from a1 where `name` =’aom‘
select id ,name,subject,grade from a1 where `name` =’jack‘
select id ,name,subject,grade from a1 where `name` =’susan‘
select id ,name,subject,grade from a1 where `name` =’rajo‘
2)在对每个临时表进行字段查询并合并结果
select `name`,count(`name`) as num from b1;
select `name`,count(`name`) as num from b2;
select `name`,count(`name`) as num from b3;
select `name`,count(`name`) as num from b4;
3、对生成的临时表c1进行having条件查询
因为此时已对表字段进行查询,所以having后条件可以直接使用别名,而where语句不行
SELECT `name`,COUNT(`name`) AS num FROM student WHERE grade < 60 GROUP BY `name` HAVING num >= 2 ;
4、对临时表进行排序查询
5、最好执行limit
执行顺序:
where 查询条件 ——> group分组 ——> 执行查询字段,包含聚合函数查询 ——>having 条件查询 ——> order排序 ——> limit
参考:https://www.cnblogs.com/fanguangdexiaoyuer/p/10268570.html