您的位置:首页 > 数据库 > MySQL

MySQL的语句执行顺序

2016-08-08 15:30 134 查看
MySQL的语句执行顺序

(1)第一种================================================================

MySQL的语句一共分为11步,如下图所标注的那样,最先执行的总是FROM操作,最后执行的是LIMIT操作。其中每一个操作都会产生一张虚拟的表,这个虚拟的表作为一个处理的输入,只是这些虚拟的表对用户来说是透明的,但是只有最后一个虚拟的表才会被作为结果返回。如果没有在语句中指定某一个子句,那么将会跳过相应的步骤。

下面我们来具体分析一下查询处理的每一个阶段

FORM: 对FROM的左边的表和右边的表计算笛卡尔积。产生虚表VT1

ON: 对虚表VT1进行ON筛选,只有那些符合的行才会被记录在虚表VT2中。

JOIN: 如果指定了OUTER JOIN(比如left join、 right join),那么保留表中未匹配的行就会作为外部行添加到虚拟表VT2中,产生虚拟表VT3, rug from子句中包含两个以上的表的话,那么就会对上一个join连接产生的结果VT3和下一个表重复执行步骤1~3这三个步骤,一直到处理完所有的表为止。

WHERE: 对虚拟表VT3进行WHERE条件过滤。只有符合的记录才会被插入到虚拟表VT4中。

GROUP BY: 根据group by子句中的列,对VT4中的记录进行分组操作,产生VT5.

CUBE | ROLLUP: 对表VT5进行cube或者rollup操作,产生表VT6.

HAVING: 对虚拟表VT6应用having过滤,只有符合的记录才会被 插入到虚拟表VT7中。

SELECT: 执行select操作,选择指定的列,插入到虚拟表VT8中。

DISTINCT: 对VT8中的记录进行去重。产生虚拟表VT9.

ORDER BY: 将虚拟表VT9中的记录按照进行排序操作,产生虚拟表VT10.

LIMIT:取出指定行的记录,产生虚拟表VT11, 并将结果返回。

(2)第二种================================================================

The actual execution of SQL statements is a bit tricky. However, the standard does specify the order of interpretation of elements in the query. This is basically in the order that you specify, although I think having and group by could come after select:

FROM clause

WHERE clause

SELECT clause

GROUP BY clause

HAVING clause

ORDER BY clause

This is important for understanding how queries are parsed. You cannot use a column alias defined in a select in the where clause, for instance, because the where is parsed before the select. On the other hand, such an alias can be in the order by clause.

As for actual execution, that is really left up to the optimizer. For instance:



group by a, b, c

order by NULL

and



group by a, b, c

order by a, b, c

both have the effect of the “order by” not being executed at all – and so not executed after the group by (in the first case, the effect is to remove sorting from the group by and in the second the effect is to do nothing more than the group by already does).

(3)第三种================================================================

SQL Select语句完整的执行顺序:

1、from子句组装来自不同数据源的数据;

2、where子句基于指定的条件对记录行进行筛选;

3、group by子句将数据划分为多个分组;

4、使用聚集函数进行计算;

5、使用having子句筛选分组;

6、计算所有的表达式;

7、使用order by对结果集进行排序。

8、select 集合输出。

关于MySQL语句的执行顺序,对select在第几步执行存在争议,第一种是《MySQL技术内幕》里说的,如上诉(1),在第8步执行,在group by之后,order by之前;第二种是上诉(2),在where之后,group by、order by之前。

个人更倾向于第三种,select最后执行,但是聚合函数、各类计算表达式会先进行计算。这就能解释

SELECT student_name FROM tb_student ORDER BY student_no;

mysql> SELECT name,sum(age) total FROM student GROUP BY name ORDER BY total;

+——-+——-+

| name | total |

+——-+——-+

| Alice | 12 |

| Bob | 45 |

+——-+——-+

因为select在order by之后执行,所以可以ORDER BY student_no,select之中没有选中的字段;因为集合函数及各类表达式在order by之前执行,所以可以ORDER BY total.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息