2010-11-12 43 views
0

我正在創建一個SQL靜態代碼分析器。 應該將以下查詢視爲包含笛卡爾連接: select t2.*
from test1 t1,
test2 t2,
test3 t3
where (t1.col1 = t2.col2
and t2.col3 = t3.col4)
or
(t1.col1 = t3.col2
and t2.col2 = t1.col1)
SQL可能的笛卡爾連接

+1

隱含的語法不應該在任何查詢更不用說複雜的使用。事實上,你必須提出這個問題是一個原因。如果您正在執行代碼分析器,則應將任何隱式連接報告爲不正確。 – HLGEM 2010-11-12 14:19:05

回答

3

不,這不是笛卡爾連接。這可能是一個糟糕的,但不是笛卡兒。

+0

感謝Octavia的快速回復。 – 2010-11-12 14:39:32

1

如果下面的查詢被視爲包含笛卡兒連接

我認爲它是如此不加分析,和我沒有要求的逗號它被rewriten。然後,我會要求它寫入沒有OR。

這裏,它是:

select t2.* 
from test2 t2 
where t2.col2 in (SELECT t1.col1 FROM test1 t1 WHERE t1.col1 is not null) 
    and t2.col3 in (SELECT t3.col4 FROM test3 t3 WHERE t3.col4 is not null) 
UNION 
select t2.* 
from test2 t2 
where t2.col2 in (SELECT t1.col1 FROM test1 t1 WHERE t1.col1 is not null) 
    and t2.col2 in (SELECT t3.col2 FROM test3 t3 WHERE t3.col2 is not null) 

或者更多的傳統:

select t2.* 
from test2 t2 
    JOIN test1 t1 ON t1.col1 = t2.col2 
    JOIN test3 t3 ON t2.col3 = t3.col4 
UNION 
select t2.* 
from test2 t2 
    JOIN test1 t1 ON t1.col1 = t2.col2 
    JOIN test3 t3 ON t2.col2 = t3.col2 
+0

感謝David的快速回復。那麼,如果代碼分析器將查詢標記爲「可能包含笛卡爾連接」,你說什麼? – 2010-11-12 14:39:59

+0

您的重寫很好地說明了爲什麼'舊式'加入仍然保留在SQL標準中(並且可能總是會),也就是說,因爲使用SQL-92中綴表示法來表示相同的聯接要複雜得多(對於人類編碼員來說)。 – onedaywhen 2010-11-12 15:10:20

+0

@onedaywhen,* shrug * - 當我看到t2。*時,我認爲通過連接引入的重複是不可取的,我將恢復爲過濾。查看我的最新編輯以獲取更傳統的JOIN(實際上它更易於編寫/讀取)。 – 2010-11-12 17:54:30