mysql语句执行顺序

  今天工作中遇到多个表关联查询需求,其实这种需求也不是今天才遇到,之前多多少少都有遇到过,个人非常不喜欢用关联查询,觉得会拖慢数据库,而且对关联查询的语句执行顺序有很多的不明白,但是今天这个需求要使用四个表关联查询,如果一个一个的查,觉得太麻烦,而且现在使用yii2.0的框架,通过hasone和joinwith函数可以很方便的关联查询,不用自己再去写sql查询语句。问题是解决了,但是对多个表的关联查询顺序的疑问却是一点也没有降低,于是就花点时间研究了下,发现一篇不错的文章。转载如下:

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

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

  1. FORM: 对FROM的左边的表和右边的表计算笛卡尔积。产生虚表VT1
  2. ON: 对虚表VT1进行ON筛选,只有那些符合<join-condition>的行才会被记录在虚表VT2中。
  3. JOIN: 如果指定了OUTER JOIN(比如left join、 right join),那么保留表中未匹配的行就会作为外部行添加到虚拟表VT2中,产生虚拟表VT3, rug from子句中包含两个以上的表的话,那么就会对上一个join连接产生的结果VT3和下一个表重复执行步骤1~3这三个步骤,一直到处理完所有的表为止。
  4. WHERE: 对虚拟表VT3进行WHERE条件过滤。只有符合<where-condition>的记录才会被插入到虚拟表VT4中。
  5. GROUP BY: 根据group by子句中的列,对VT4中的记录进行分组操作,产生VT5.
  6. CUBE | ROLLUP: 对表VT5进行cube或者rollup操作,产生表VT6.
  7. HAVING: 对虚拟表VT6应用having过滤,只有符合<having-condition>的记录才会被 插入到虚拟表VT7中。
  8. SELECT: 执行select操作,选择指定的列,插入到虚拟表VT8中。
  9. DISTINCT: 对VT8中的记录进行去重。产生虚拟表VT9.
  10. ORDER BY: 将虚拟表VT9中的记录按照<order_by_list>进行排序操作,产生虚拟表VT10.
  11. LIMIT:取出指定行的记录,产生虚拟表VT11, 并将结果返回。

再引用一段书上的解释

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).

原文地址:https://www.cnblogs.com/dawq/p/5260998.html