2012-07-26 71 views
1

我有4個表,並且4是外鍵在一個聯結表中。如何檢查表中是否存在多對多...

問題是我需要檢索缺少的jnction值。

例如:

Table A  Table B  Table C  Table D    
--------  --------- --------- ---------- 
    1    4   7   A 
    2    5   8   B 



JUNCTION TABLE 
----------------- 
    1 4 7 A 
    1 4 7 B 
    1 4 8 A 
    1 4 8 B 
    1 5 7 A 
    1 5 7 B 
    1 5 8 A 
    1 5 8 B  
    2 4 7 A 
    2 4 7 B 
    2 4 8 A 
    2 4 8 B 
    2 5 7 A 
    2 5 7 B 
    2 5 8 A 
    2 5 8 B  

因此,如果列1 5 8 B丟失,當我運行查詢它示出了1 5 8乙..

任何想法?

回答

1

我會在源表上使用交叉連接,然後將其結果加入到聯結表中。

編輯:安迪holaday指出,MySQL沒有完全外部聯接的榮譽。

select x.* 
from (select * 
     from a,b,c,d) as x 
left outer join j 
    on (x.a = j.a and 
     x.b = j.b and 
     x.c = j.c and 
     x.d = j.d) 
where j.a is NULL and 
     j.b is NULL and 
     j.c is NULL and 
     j.d is NULL 
+0

正確的想法,但[MySQL不支持FULL OUTER JOIN(HTTP://計算器.com/q/3362079/1248931),所以你需要將它作爲'RIGHT JOIN'並且測試'NULL'的所有'j'列。你也有一個錯字:'j.d = j.d)' – 2012-07-26 01:39:03

+0

好點,謝謝!一半T-SQL在這裏進行。它已被編輯。而錯字......好吧......我會責備我通過手機回答! – pyrospade 2012-07-26 02:48:57

+0

謝謝,完美的作品。 – RLuceac 2012-07-26 12:28:01

0

使用此查詢,這並外從4個表連接到路口交叉連接:

select a.col, b.col, b.col, d.col 
from tablea a 
cross join tableb b 
cross join tablec c 
cross join tabled d 
left join junction j 
    on j.cola = a.col 
    and j.colb = b.col 
    and j.colc = c.col 
    and j.cold = d.col 
where junction.cola is null; -- sufficient to test just one