之前一直没着重了解过 SQL 语句
SQL 语句的执行顺序有利于对 SQL 进行调优
今天记一下 SQL 顺序口诀
从筛分,再筛选排定。
从 (from) 筛(where)分 (group by),再筛(having) 选(select)排 (order by) 定(limit)。
顺序即为:
from(这里还包括 join 和 on) -> where -> group by -> having -> select -> order by -> limit
补充:
还有聚合函数的执行顺序,聚合函数又叫做分组函数,自然排在了 group by 后面。也就是口诀的逗号部分。
因为聚合函数的计算顺序排在了分组之后,更排在了 where 之后,所以 where 中不可以使用聚合函数。
当我尝试在 where 中使用聚合函数时,报错如下
mydb=# select * from employees where salary > avg(salary);
ERROR: aggregate functions are not allowed in WHERE
LINE 1: select * from employees where salary > avg(salary);
当然,可以通过子查询的方式先获取一下平均值
select * from employees where salary > (select avg(salary) from employees);
因为 limit 排在最后,所以 limit 1 和 limit 1000 可能差别不大,这里 1000 是个虚数。
因为不管是否 limit,之前其实都已经 select 过了。
另外 order by 的资源消耗量是最大的。