我一直在努力寻找答案,但….
有人可以向我解释将JOIN的ON条件与JOIN本身之间的区别,同时将ON置于所有其他JOIN结束处.
有人可以向我解释将JOIN的ON条件与JOIN本身之间的区别,同时将ON置于所有其他JOIN结束处.
这里是一个例子http://sqlfiddle.com/#!3/e0a0f/3
CREATE TABLE TableA (Email VARCHAR(100),SomeNameA VARCHAR(100)) CREATE TABLE Tableb (Email VARCHAR(100),SomeNameB VARCHAR(100)) CREATE TABLE Tablec (Email VARCHAR(100),SomeNameC VARCHAR(100)) INSERT INTO TableA SELECT 'joe@test.com','JoeA' INSERT INTO TableA SELECT 'jan@test.com','JaneA' INSERT INTO TableA SELECT 'dave@test.com','DaveA' INSERT INTO TableB SELECT 'joe@test.com','JoeB' INSERT INTO TableB SELECT 'dave@test.com','DaveB' INSERT INTO TableC SELECT 'joe@test.com','JoeC' INSERT INTO TableC SELECT 'dave@test.com','DaveC' SELECT TOP 2 a.*,b.*,c.* FROM TableA a LEFT OUTER JOIN TableB b ON a.email = b.email INNER JOIN TableC c ON c.Email = b.email; SELECT TOP 2 a.*,c.* FROM TableA a LEFT OUTER JOIN TableB b INNER JOIN TableC c ON c.Email = b.email ON a.email = b.email;
我不明白为什么这两个SELECT语句产生不同的结果.
解决方法
重要的是联接订单.处理你的表达式,就像每个连接都产生临时的“虚拟”表.
所以当你写
FROM TableA a LEFT OUTER JOIN TableB b ON a.email = b.email INNER JOIN TableC c ON c.Email = b.email ;
那么订单如下:
> TableA与TableB相连接,生成临时关系V1
> V1内部连接到TableC.
当你写的时候,
FROM TableA a LEFT OUTER JOIN TableB b INNER JOIN TableC c ON c.Email = b.email ON a.email = b.email;
那么订单如下:
> TableB内部连接到TableC生成临时关系V1.
> TableA被连接到V1.
因此,结果是不同的.通常建议在这种情况下使用括号来提高查询的可读性:
FROM TableA a LEFT OUTER JOIN (TableB b INNER JOIN TableC c ON c.Email = b.email) ON a.email = b.email;