SQL语句的执行顺序

一.sql语句的执行顺序

 1 (8)SELECT  (9) DISTINCT  (11)  <TOP_specification> <select_list> 
 2 
 3 (1)  FROM <left_table>  
 4 
 5 (3) <join_type> JOIN <right_table> 
 6 
 7 (2) ON <join_condition> 
 8 
 9 (4) WHERE <where_condition> 
10 
11 (5) GROUP BY <group_by_list> 
12 
13 (6) WITH {CUBE | ROLLUP} 
14 
15 (7) HAVING <having_condition> 
16 
17 (10) ORDER BY <order_by_list>

 

二.测试left join和 where的执行顺序

 1 创建测试表
 2 create table t1(id int,feild int);
 3 create table t2(id int,feild int);
 4 
 5 insert into t1 values(1,1);
 6 insert into t1 values(1,2);
 7 insert into t1 values(1,3);
 8 insert into t1 values(1,4);
 9 insert into t1 values(2,1);
10 insert into t1 values(2,2);
11 
12 insert into t2 values(1,1);
13 insert into t2 values(1,2);
14 insert into t2 values(1,5);
15 insert into t2 values(1,6);
16 insert into t2 values(2,1);
17 insert into t2 values(2,3);
1 测试 语句:
2 select t1.*,t2.* from t1 left join t2 on t1.id=t2.id
3 select t1.*,t2.* from t1 left join t2 on t1.id=t2.id and t1.id=1
4 select t1.*,t2.* from t1 left join t2 on t1.id=t2.id where t1.id=1
5 select t1.*,t2.* from t1 left join t2 on t1.id=t2.id and t2.id=1
6 select t1.*,t2.* from t1 left join t2 on t1.id=t2.id where t2.id=1
7 select t1.*,t2.* from t1 inner join t2 on t1.id=t2.id and t2.id=1

 

结论:

结论:取t1表的第一行,按谓词‘on’中的条件扫瞄t2表,如果满足条件,就加入返回结果表,不满足条件则只返回t1.
然后取t1表的第二行,按谓词‘on’中的条件扫瞄t2表,如果满足条件,就加入返回结果表,不满足条件则只返回t1.
重复以上过程,直到t1表扫描结束

 

 

结论:

结论:取t1表的第一行,按谓词‘on’中的条件扫瞄t1,t2表,如果满足条件,就加入返回结果表,不满足条件则只返回t1.
然后取t1表的第二行,按谓词‘on’中的条件扫瞄t2表,如果满足条件,就加入返回结果表,不满足条件则只返回t1.
重复以上过程,直到t1表扫描结束

 

 

结论:

 

 

 

 

 

结论:

 

 

结论:

 

 

结论:

 

posted @ 2016-03-09 16:53  PoleStar  阅读(1696)  评论(0编辑  收藏  举报