标签:
今天工作中遇到多个表关联查询需求,其实这种需求也不是今天才遇到,之前多多少少都有遇到过,个人非常不喜欢用关联查询,觉得会拖慢数据库,而且对关联查询的语句执行顺序有很多的不明白,但是今天这个需求要使用四个表关联查询,如果一个一个的查,觉得太麻烦,而且现在使用yii2.0的框架,通过hasone和joinwith函数可以很方便的关联查询,不用自己再去写sql查询语句。问题是解决了,但是对多个表的关联查询顺序的疑问却是一点也没有降低,于是就花点时间研究了下,发现一篇不错的文章。转载如下:
MySQL的语句一共分为11步,如下图所标注的那样,最先执行的总是FROM操作,最后执行的是LIMIT操作。其中每一个操作都会产生一张虚拟的表,这个虚拟的表作为一个处理的输入,只是这些虚拟的表对用户来说是透明的,但是只有最后一个虚拟的表才会被作为结果返回。如果没有在语句中指定某一个子句,那么将会跳过相应的步骤。
再引用一段书上的解释
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).
标签:
原文地址:http://www.cnblogs.com/dawq/p/5260998.html