2013-09-16 19 views
0

請參閱下面的DDL:SQL ON子句v,其中第(不同的結果)

CREATE TABLE TestTable(id int, [name] varchar(30)) 
CREATE TABLE TestTable2(id int, [name] varchar(30)) 

INSERT INTO TestTable (id,[name]) values (1,'') 
INSERT INTO TestTable (id,[name]) values (2,'Martin') 

INSERT INTO TestTable2 (id,[name]) values (1,null) 
INSERT INTO TestTable2 (id,[name]) values (2,'Martin') 

select TestTable.* from TestTable 
LEFT JOIN TestTable2 
ON TestTable.id=TestTable2.id 
and TestTable.[name]= TestTable2.[Name] and NOT (TestTable.[name] ='' and TestTable2.[name] is null) 
where testtable2.id is null 

的SELECT返回一行,我希望它返回None。我期望它沒有返回的原因與下面的SQL語句返回無相同的原因:

select TestTable.* from TestTable 
LEFT JOIN TestTable2 
ON TestTable.id=TestTable2.id 
and TestTable.[name]= TestTable2.[Name] 
where testtable2.id is null and NOT (TestTable.[name] ='' and TestTable2.[name] is null) 

爲什麼第一個SQL語句返回一行? ON子句應該用這個標準將這些記錄歸檔:NOT(TestTable。[name] =''和TestTable2。[name]爲空)。返回的一行包含此條件。爲什麼?

回答

5

一個LEFT JOIN將返回左表中的所有行,除非它們被WHERE標準過濾掉了,你的第一個查詢WHERE標準不包括1行,在你的第二個查詢WHERE排除兩行。

更新:瞭解A流行參考加入的是:
Visual Representation of SQL Joins

ON用於定義表將如何連接在一起,WHERE限制結果。在INNER JOIN的情況下,它們都限制了結果,OUTER JOIN它們之間的差異變得可觀。

+0

同意。我只能在工作中自己處理這個問題。添加一個檢查左連接部分的where過濾器,它基本上被視爲內連接,因爲它必須符合過濾器的條件。 –

+0

謝謝。我認爲ON子句決定了左表中的內容(我顯然是錯的)。有什麼文件可以提及嗎? +1。 – w0051977

+0

當然,看到更新。 –