create table temp1
(
aid VARCHAR(5) not null,
car VARCHAR(10) not null
);
create table temp2
(
bid VARCHAR(5) not null,
username VARCHAR(10) not null
);
create table temp3
(
cid VARCHAR(5) not null,
dogname VARCHAR(10) not null
);
insert into temp1(aid,car) values('001','benz');
insert into temp1(aid,car) values('001','BMW');
insert into temp1(aid,car) values('001','ford');
insert into temp1(aid,car) values('001','jeep');
insert into temp1(aid,car) values('002','jeep');
insert into temp1(aid,car) values('003','hongqi');
insert into temp2(bid,username) values('001','mayun');
insert into temp3(cid,dogname) values('001','lily');
insert into temp3(cid,dogname) values('001','lucy');
insert into temp3(cid,dogname) values('002','xiaohua');
SQL的逻辑顺序如下:
1. FROM
1.1. JOIN
1.2. ON
2. WHERE
3. GROUP BY
4. WITH CUBE or WITH ROLLUP
5. HAVING
6. SELECT
7. DISTINCT
8. ORDER BY
11. TOP
在实际中,ANSI JOIN的优先级高于FROM平铺连接的优先级,对于外关联,通常但不绝对会先生成子查询。JOIN中NATURAL,USING,ON只能三者选一,而且是语法解析器控制,对于NATURAL,语法分析器会自动加上对应的USING。有了USING后,就会填充qual等值过滤条件。如果写了USING,则写了啥就是啥、和WHERE一样。
示例,
select * from temp2 a2,temp1 a1 left join temp3 a3 on a1.aid=a3.cid where a1.aid=a3.cid;
通过on过滤,left join就近连a1表,之后生成临时表,和a2一起参与where。所以,结果为:
对于语句,这结果为:
无论是mysql、oracle还是postgresql,结果是一样的。
from 平铺定义在SQL 89中,ANSI JOIN定义在SQL 92中,见iso sql高级特性及定义的版本。