sql执行顺序

2015/10/25

下面是SELECT语句的逻辑执行顺序:

FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP

几个示例

第一个示例

SELECT ID,COUNT(ID) AS TOTAL
FROM STUDENT
GROUP BY ID
HAVING TOTAL>2

实际执行顺序如下:

FROM STUDENT
GROUP BY ID
HAVING TOTAL>2
SELECT ID,COUNT(ID) AS TOTAL

TOTAL是在最后一句SELECT ID,COUNT(ID) AS TOTAL执行过后生成的新别名。因此,在HAVING TOTAL>2执行时是不能识别TOTAL的。

第二个示例

SELECT ID,COUNT(ID) AS TOTAL
FROM STUDENT
GROUP BY ID
ORDER BY TOTAL

实际执行顺序是:

FROM STUDENT
GROUP BY ID
SELECT ID,COUNT(ID) AS TOTAL
ORDER BY TOTAL

第三个示例

SELECT ID,COUNT(ID) AS TOTAL
FROM STUDENT
GROUP BY ID
ORDER BY COUNT(ID)

实际执行顺序:

FROM STUDENT
GROUP BY ID
SELECT ID,COUNT(ID) AS TOTAL
ORDER BY COUNT(ID)

第四个示例

SELECT FIRSTNAME+’ ‘+LASTNAME AS NAME, COUNT(*) AS COUNT
FROM STUDENT
GROUP BY NAME

实际执行顺序:

FROM STUDENT
GROUP BY NAME
SELECT FIRSTNAME+’ ‘+LASTNAME AS NAME,COUNT(*) AS COUNT

Reference

http://blog.sae.sina.com.cn/archives/3740