在MySQL中执行子句的预定义顺序是什么?有些是在运行时决定的,这个顺序是否正确?
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
答案 0 :(得分:49)
MySQL语句的实际执行有点棘手。但是,该标准确实指定了查询中元素的解释顺序。这基本上是您指定的顺序,但我认为HAVING
和GROUP BY
可能会在SELECT
之后出现:
FROM
条款WHERE
条款SELECT
条款GROUP BY
条款HAVING
条款ORDER BY
条款这对于理解如何解析查询非常重要。例如,您不能在SELECT
子句中使用WHERE
中定义的列别名,因为WHERE
在SELECT
之前被解析。另一方面,这样的别名可以在ORDER BY
子句中。
至于实际执行,这实际上是由优化器决定的。例如:
. . .
GROUP BY a, b, c
ORDER BY NULL
和
. . .
GROUP BY a, b, c
ORDER BY a, b, c
两者都具有ORDER BY
根本没有执行的效果 - 因此在GROUP BY
之后没有执行(在第一种情况下,效果是从{{1}中删除排序而在第二个效果是只做GROUP BY
已经做的事情。
答案 1 :(得分:1)
这是你如何大致了解mysql如何执行选择查询
DROP TABLE if exists new_table;
CREATE TABLE `new_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`testdecimal` decimal(6,2) DEFAULT NULL,
PRIMARY KEY (`id`));
INSERT INTO `new_table` (`testdecimal`) VALUES ('1234.45');
INSERT INTO `new_table` (`testdecimal`) VALUES ('1234.45');
set @mysqlorder := '';
select @mysqlorder := CONCAT(@mysqlorder," SELECT ") from new_table,(select @mysqlorder := CONCAT(@mysqlorder," FROM ")) tt
JOIN (select @mysqlorder := CONCAT(@mysqlorder," JOIN1 ")) t on ((select @mysqlorder := CONCAT(@mysqlorder," ON1 ")) or rand() < 1)
JOIN (select @mysqlorder := CONCAT(@mysqlorder," JOIN2 ")) t2 on ((select @mysqlorder := CONCAT(@mysqlorder," ON2 ")) or rand() < 1)
where ((select @mysqlorder := CONCAT(@mysqlorder," WHERE ")) or IF(new_table.testdecimal = 1234.45,true,false))
group by (select @mysqlorder := CONCAT(@mysqlorder," GROUPBY ")),id
having (select @mysqlorder := CONCAT(@mysqlorder," HAVING "))
order by (select @mysqlorder := CONCAT(@mysqlorder," ORDERBY "));
select @mysqlorder;
这里是mysql查询的输出,希望你能搞清楚 SELECT 查询的mysql执行: -
FROM JOIN1 JOIN2 WHERE ON2 ON1 ORDERBY GROUPBY SELECT WHERE ON2 ON1 ORDERBY GROUPBY SELECT HAVING
答案 2 :(得分:-3)
我认为执行顺序是这样的:
(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>[, <offset_number>]