对数据库基本操作是每个程序员基本功,如何理解并快速记住sql执行的顺序呢,其实一条复杂的sql就能搞定:
SELECT DISTINCT <select_list>
FROM <left_table>
<join_type> JOIN <right_table>
ON <join_condition>
WHERE <where_condition>
GROUP BY <group_by_list>
HAVING <having_condition>
ORDER BY <order_by_condition>
LIMIT <limit_number>
执行顺序:
(7) SELECT
(8) DISTINCT <select_list>
(1) FROM <left_table>
(3) <join_type> JOIN <right_table>
(2) ON <join_condition>
(4) WHERE <where_condition>
(5) GROUP BY <group_by_list>
(6) HAVING <having_condition>
(9) ORDER BY <order_by_condition>
(10) LIMIT <limit_number>
另外需要注意的问题:
(1)group by 存在时,select中除了聚集函数外,所有的基本列必须是group by里面存在的;having基本上同group by一起使用的,having类似于where语句,只是having过滤是基于group by 分组后的数据,having一般通过select语句里面的聚集函数进行过滤。
参考:
http://www.cnblogs.com/Qian123/p/5666569.html
http://www.cnblogs.com/Qian123/p/5669259.html#_label10