天天看点

SQL语句执行顺序是什么样的呢

(SQL语句执行顺序是什么样的呢)

select语句定义如下:

<SELECT clause> [<FROM clause>] [<WHERE clause>] [<GROUP BY clause>] [<HAVING clause>] [<ORDER BY clause>] [<LIMIT clause>] 
           

先给出SQL语句执行顺序结论,后通过案例分析:

  1. 最先执行from tab;
  2. where语句是对条件加以限定;
  3. 执行分组语句group by
  4. 执行分组函数
  5. 执行分组后过滤having
  6. select语句。
  7. order by排序语句。

Select 6

...

分组函数(avg、sum等) 4

...

From 1

...

where 2

...

group by 3

...

having 5

...

order by 7

案例SQL执行分析

select deptno ,avg(sal) from emp where ename is not null group by deptno having avg(sal)>2000 order by deptno desc;
           
  1. 先确定从哪个表中取数据,所以最先执行from emp。如果存在多表连接,from tab1,tab2。可以对表加别名,方便后面的引用。
  2. 执行 where子句, 筛选 emp 表中ename数据不为 null的数据 。
  3. 执行 group by 子句, 把 emp 表按 "deptno" 进行分组。
  4. 执行 avg(sal) 分组函数, 按分组计算平均工资(sal)数值。 (常用的聚合函数有max,min, count,sum,聚合函数的执行在group by之后,having之前。如果在where中写聚合函数,就会出错。)
  5. 执行 having 子句, 筛选平均薪资大于2000的。
  6. 执行select选出要查找的字段,如果全选可以select *。这里选出部门编号,各部门平均工资。
  7. 执行order by 排序语句。order by语句在最后执行,只有select选出要查找的字段,才能进行排序。