2011-02-23 53 views
1

我對我的SQL查詢有點麻煩。SQL CROSS JOIN問題

我有兩個表:

表1

id guid title  D0  D1  D2 
----------------------------------------- 
1 guid1 Title1 0.123 -0.235 0.789 
2 guid2 Title2 -0.343 0.435 0.459 
3 guid3 Title3 0.243 -0.267 -0.934 
... 
100 guid4 Title100 -0.423 0.955 0.029 

和表2(注意它具有相同的架構,只是不同的數據)。

id guid title  D0  D1  D2 
---------------------------------------- 
1 guid1 Title1 0.233 -0.436 -0.389 
2 guid2 Title2 -0.343 0.235 0.789 
3 guid3 Title3 0.573 -0.067 -0.124 
... 
100 guid4 Title100 -0.343 0.155 0.005 

我試圖找出如何寫一個SELECT語句返回所有的冠軍WHERE所有的ABS(Table1_D0*Table2_D0)+ABS(Table1_D1*Table2_D1)+ABS(Table1_D2*Table2_D2)組合小於定限值(可能是硬編碼)。

到目前爲止,我正在嘗試使用CROSS JOIN,但我不確定這是否是正確的方法。

這是否有意義? 表1 row1針對表2的所有行,然後表1針對表2的所有行的所有行。

如果重要,我正在使用MS SQL。

非常感謝! 佈雷特

回答

6
SELECT t1.title 
FROM Table1 t1 
CROSS JOIN table2 t2 
WHERE ABS(t1.D0*t2.D0)+ABS(t1.D1*t2.D1)+ABS(t1.D2*t2.D2)<10 
+0

有DB時,不支持交叉連接的替代語法?例如SQL 2000 – 2011-02-23 20:48:39

+1

@Conrad'SELECT t1.title FROM Table1 t1,table2 t2'將是相同的 – Magnus 2011-02-23 21:05:26

+0

@Conrad Frix,SQL Server 2000確實支持上面的語法。 – HLGEM 2011-02-23 21:14:20

0

CROSS JOIN是正確的選擇,CROSS JOIN是一樣的,因爲沒有參加在所有(見Snowbear答案)。

0
SELECT * 
    FROM Table1 a inner join 
     Table2 b on a.Id=b.Id 
where ABS(a.D0*b.D0)+ABS(a.D1*b.D1)+ABS(a.D2*b.D2)<[email protected] 
0
select t1o.title 
from Table1 t1o 
where not exists 
(
    -- none of the cross-joined rows for t1o must be above the threshold 
    select t1.title 
    from Table1 t1 
    cross join Table2 t2 
    where t1.id = t1o.id -- only the cross joined rows for the current t1o row 
    -- inverted b/c not exists 
    and abs(t1.D0*t2.D0)+abs(t1.D1*t2.D1)+abs(t1.D2*t2.D2) > 10 
)