MySQL query / clause execution order

mysql的语句的执行顺序,因为今天和文佳在做查询的时候,有如下的sql:

 

select Xrow as newName

from Xtable

group by Xrow

having newName > 12;

 

很明显有一个问题 having 使用了select里面的语句,为毛呀,明明having的执行在select前面(我记得是)

 

百度一下

 

 

结论上面说了having是7 select是8 ,这太不可思议了~

 

没办法,不相信事实~

google it

http://stackoverflow.com/questions/24127932/mysql-query-clause-execution-order

 

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

问题解决~看来查资料还是要看google

 

 





posted @ 2015-11-23 20:16  一行白龙上青天  阅读(417)  评论(0编辑  收藏  举报